Python os.ftruncate() Method



The Python os.ftruncate() method truncates the data from the end of a file corresponding to the given file descriptor. It will reduce the file data to a specified length.

If the specified length is greater than or equal to the size of the file, the file remains unchanged.

Syntax

Following is the syntax for ftruncate() method −

os.ftruncate(fd, length)

Parameters

The Python os.ftruncate() method accepts the following parameters −

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

  • length − This is the length of the file where file needs to be truncated.

Return Value

The Python os.ftruncate() method does not return any value.

Example

The following example shows the usage of ftruncate() method. Here, we open a file in read/write mode and then remove the file data except the first 10 bytes.

#!/usr/bin/python
import os, sys

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

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

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

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

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

When we run above program, it produces following result −

The available String :  b'This is te'
Closed the file successfully!!

Example

In the following example, we are using os.ftruncate() method with a File Objects. We use the "with" statement to open and close the file. We write a string to the file, truncate it to eight bytes, and then read from the beginning to print the remaining string.

import os

# Open a file 
with open("foo.txt", "r+") as file:
    # Writing to the file
    file.write("Python with Tutorialspoint")
    
	# Flush the write buffer
    file.flush()
	
    # get the file descriptor
    fd = file.fileno()

    # Truncating the file
    os.ftruncate(fd, 8)

    # Read the file
    file.seek(0)
    print(file.read())

On executing the above program, it produces following result −

Python w
python_files_io.htm
Advertisements