What is the os.truncate() method in Python?
Overview
The OS module in Python provides an interface to utilize the functionality of the underlying operating system.
The os.truncate() method allows us to shorten the size of the file to the given length. It reduces the size of the file from the top.
Syntax
# Signatureos.truncate(file ,length)
Parameters
It takes the following argument values.
file: This is the file descriptor of the directory or the file to be truncated.length: This is the length of the file to which it is to be truncated.
Return value
By default, it does not return any value.
Code
In the below example, we have 50 bytes. Therefore, the file path will be 50 bytes, and the rest of the bytes will be terminated. Finally, it returns a new file. It is mainly supported as a file descriptor as well.
main.py
data.txt
#Import OS moduleimport os# Opening and printing the size of "file.txt"file = open("data.txt", "a")#getsize() method is used to get the size of the file.txtsize1 = os.path.getsize('data.txt')#Print the size of the file in bytesprint (f"The file size is {size1} bytes")# Truncate the file up to 40 bytes and find the size againfile.truncate(50)#Getsize() method used gain to get the size of the filesize2 = os.path.getsize('data.txt')#Print the size againprint (f"The file size is {size2} bytes")# Close the filefile.close()
Explanation
- Line 2: We import the OS module.
- Line 5: We open the file named
data.txt. - Line7: We get the size of the file with the
getsize()method. - Line 9: We print the file's size in bytes. We then use the truncate method and add 50 bytes to its size.
- Line 15: We get the size of a file to distinguish the difference.
- Line 17: We see the difference before using the truncate method and after using it.