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.
# Signatureos.truncate(file ,length)
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.By default, it does not return any value.
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.
#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()
data.txt.
getsize()
method.