Python2.x Python os.ftruncate() Method

Python OS File/Directory Methods


Overview

The os.ftruncate() method truncates the file corresponding to the file descriptor fd, so that it is at most length bytes in size.

Available on Unix and Windows.

Syntax

The syntax for the ftruncate() method is:

os.ftruncate(fd, length)

Parameters

  • fd -- The file descriptor of the file.
  • length -- The size to truncate the file to.

Return Value

This method does not return a value.

Example

The following example demonstrates the use of the ftruncate() method:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# Open the file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write a string
os.write(fd, "This is test - This is test")

# Use ftruncate() method
os.ftruncate(fd, 10)

# Read the content
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print("The string is : "), str

# Close the file
os.close( fd)
print("Closed the file successfully!!")

Executing the above program outputs the following result:

The string is :  This is te
Closed the file successfully!!

Python OS File/Directory Methods