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 |
Return Values
The truncate()
method returns an int
representing the new file size.
How to Use truncate()
in Python
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!'