The truncate()
method in Python resizes the file to a specified size. If no size is given, it uses the current file position.
The truncate()
method is declared with a file object, as follows:
This method has one optional parameter, size
, which is the number of bytes up to which the file needs to be resized.
There is no return value of the
truncate()
method. However, after you correctly apply truncate()
to a file, its increased size can be checked in the file’s properties.
In the example below, the my_file.txt
file is initially 20 bytes large. Then, it is truncated up to 40 bytes with the truncate()
method.
import os# Opening and printing the size of "my_file.txt"f = open("my_file.txt", "a")file_size = os.path.getsize('my_file.txt')print "The file size is", file_size, "bytes"# Truncate the file up to 40 bytes and find size againf.truncate(40)file_size2 = os.path.getsize('my_file.txt')print "The file size is", file_size2, "bytes"# Close the filef.close()
Here, the truncate()
method is used without any parameter, so it uses the current file size.
import os# Opening and printing the size of "my_file.txt"f = open("second_file.txt", "a")file_size = os.path.getsize('second_file.txt')print "The file size is", file_size, "bytes"# Truncate without any sepcified size and find the size againf.truncate()file_size2 = os.path.getsize('second_file.txt')print "The file size is", file_size2, "bytes"# Close the filef.close()