What is truncate() in Python?

The truncate() method in Python resizes the file to a specified size. If no size is given, it uses the current file position.

Syntax

The truncate() method is declared with a file object, as follows:

The syntax of truncate() method in Python

Parameter and return value

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.

Example

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.

main.py
my_file.txt
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 again
f.truncate(40)
file_size2 = os.path.getsize('my_file.txt')
print "The file size is", file_size2, "bytes"
# Close the file
f.close()

Here, the truncate() method is used without any parameter, so it uses the current file size.

main.py
second_file.txt
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 again
f.truncate()
file_size2 = os.path.getsize('second_file.txt')
print "The file size is", file_size2, "bytes"
# Close the file
f.close()

Free Resources