Python - File truncate() Method


Advertisements

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.

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 "a" or "a+" mode.

MyFile = open("python_test.txt", "a")
#current file stream position is zero.
#file is truncated after 0 bytes.
MyFile.truncate()
MyFile.close()

MyFile = open("python_test.txt", "a+")
#read first 10 bytes of the file
print(MyFile.read(10))
#current file stream position is 10.
#file is truncated after 10 bytes.
MyFile.truncate()
MyFile.close()

MyFile = open("python_test.txt", "a")
#file is truncated to 10 byte size
MyFile.truncate(10)
MyFile.close()

Python File Handling Methods
Advertisements