Python OS file/directory os.ftruncate() method

Python OS File/Directory os.ftruncate() Method

Description

The ftruncate() method truncates the file corresponding to file descriptor fd to a size of at most length bytes.

Syntax

The syntax of the ftruncate() method is as follows:

os.ftruncate(fd, length)

Parameters

  • fd − This is the file descriptor to be truncated.
  • length − This is the length to which the file is to be truncated.

Return Value

This method does not return any value. Available on Unix-like systems.

Example

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

import os, sys

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

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

# Now you can use ftruncate() method.
os.ftruncate(fd, 10)

# Now read this file from the beginning.
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("Read String is : ", str)

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

When we run the above program, it will produce the following output −

Read String is: This is te
Closed the file successfully!!

Leave a Reply

Your email address will not be published. Required fields are marked *