Python os.ftruncate() – Truncates the file corresponding to file descriptor fd
Python | os.ftruncate() Method
Python The os.ftruncate() method truncates the file corresponding to file descriptor fd to a size of at most length bytes.
Syntax: os.ftruncate(fd, length)
Parameters:
fd: This is the file descriptor to be truncated.
length: This is the length of the file to be truncated.
Return Value: This method does not return any value.
Example 1
Use the os.ftruncate() method to truncate the file
# Python program to explain os.ftruncate() method
# importing os module
import os
# path
path = 'C:/Users/Rajnish/Desktop/testfile.txt'
#Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_RDWR|os.O_CREAT)
# String to be written
s = 'GeeksforGeeks'
# Convert the string to bytes
line = str.encode(s)
# Write the bytestring to the file
# associated with the file
# descriptor fd
os.write(fd, line)
# Using os.ftruncate() method
os.ftruncate(fd, 5)
# Seek the file from beginning
# using os.lseek() method
os.lseek(fd, 0, 0)
# Read the file
s = os.read(fd, 15)
# Print string
print(s)
# Close the file descriptor
os.close(fd)
Output:
b'Geeks'
Example 2
Use the os.ftruncate() method to truncate the file
# Python program to explain os.ftruncate() method
# importing os module
import os
# path
path = 'C:/Users/Rajnish/Desktop/testfile.txt'
#Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_RDWR|os.O_CREAT)
# String to be written
s = 'GeeksforGeeks - Computer Science portal'
# Convert the string to bytes
line = str.encode(s)
# Write the bytestring to the file
# associated with the file
# descriptor fd
os.write(fd, line)
# Using os.ftruncate() method
os.ftruncate(fd, 10)
# Seek the file from beginning
# using os.lseek() method
os.lseek(fd, 0, 0)
# Read the file
s = os.read(fd, 15)
# Print string
print(s)
# Close the file descriptor
os.close(fd)
Output:
b'GeeksforGe'