Python File truncate() Method

Example

Open the file with "a" for appending, and then truncate the file to 20 bytes:

f = open("demofile2.txt", "a")
f.truncate(20)
f.close()
#open and read the file after the truncate:
f = open("demofile2.txt", "r")
print(f.read())

Running Example

Definition and Usage

The truncate() method adjusts the file size to the specified number of bytes.

If the size is not specified, the current position will be used.

Syntax

file.truncate(Size)

Parameter Value

Parameter Description
Size Optional. The size of the truncated file (in bytes). Default value: None, indicating the current position of the file stream.