Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


The Python file truncate() method is used to truncate the file's size. This methods has one optional parameter which can be used to specify the size of the file in bytes after the truncate.

Syntax

file.truncate(size)

Parameters

size Optional. specify size of the file in bytes after the truncate. Default is current file stream position.

Return Value

None.

Example: truncate a file in Python

In the below example, Python file truncate() method is used to truncate a file called MyFile. The file is opened in the append mode using append mode.

MyFile = open("python_test.txt", "a")

#Assuming the file contains
#This is line 1 content.
#This is line 2 content.
#This is line 3 content.

#file is truncated to 30 byte size
MyFile.truncate(30)
MyFile.close()

#content of the file after truncate
MyFile = open("python_test.txt", "r")
print(MyFile.read())
MyFile.close()

The output of the above code will be:

This is line 1 content.
This 

❮ Python File Handling Methods