Skip to main content

truncate()

The truncate() method in Python is a file method used to resize the file to a specified size. If the optional size parameter is not provided, it truncates the file to the current position. If the size parameter is less than the current file size, the extra data will be lost. If the size parameter is greater than the current file size, the file size will be increased and null bytes will be added as needed.

Parameter Values

Parameter Description
size

The optional size parameter represents the new size of the file, specified in bytes. If omitted or negative, the file's size will be truncated to the current file position.

Return Values

The truncate() method returns an int representing the new file size.

How to Use truncate() in Python

Example 1:

The truncate() method is used to resize the file to a specified size. If the optional size parameter is not specified, it truncates the file to a size of 0.

with open('file.txt', 'w+') as file:
    file.write('Hello, World! This file will be truncated.')
    file.truncate(15)
    print(file.read())
# Output: 'Hello, World!'