Python Tutorial Python Advanced Python References Python Libraries

Python - File truncate() Method



The Python 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

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, truncate() method is used to truncate the given file.

#reading file before truncation
print("Before truncation file contains:")
MyFile = open("test.txt", "r")
print(MyFile.read())
MyFile.close()

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

#reading file after truncation
print("\nAfter truncation file contains:")
MyFile = open("test.txt", "r")
print(MyFile.read())
MyFile.close()

The output of the above code will be:

Before truncation file contains:
This is a test file.
It contains dummy content.

After truncation file contains:
This is a test file.
It 

❮ Python File Handling Methods