Python 3 – os.ftruncate() Method
In Python programming, the os.ftruncate()
method is used to truncate the file descriptors pointed to by the file descriptor file to a size of size
bytes. If the file is larger than the specified size, the remaining data is lost.
Syntax
os.ftruncate(fd, length)
Parameters
fd
: A file descriptor number, that is obtained using theos.open()
method.length
: A required length, to which the file specified infd
needs to be truncated.
Return Value
The os.ftruncate()
method returns None
if the file size is successfully truncated as per the specified length value.
Example
Here is an example that demonstrates how the os.ftruncate()
method works:
import os
# Open an existing file, in write mode and truncate the file
fd = os.open("example.txt", os.O_RDWR|os.O_TRUNC)
# Write some data to the file
os.write(fd, bytes("This is a sample text.", 'utf-8'))
# Get the size of the file
size = os.path.getsize("example.txt")
# Truncate the file to a length of 40 bytes
os.ftruncate(fd, 40)
# Display the truncated file size
print(os.path.getsize("example.txt"))
# Close the file descriptor
os.close(fd)
Output:
40
Conclusion
In conclusion, the os.ftruncate()
method is an important Python method that can be used to truncate a file descriptor to a specified length in bytes. This method is essential when working with large files and when you need to free up space in the file. By understanding how os.ftruncate()
works, you can add powerful functionality to your Python projects, and better manage your files.