Resize or truncate text file to specific size in Python
To resize or truncate a text file to specific size in Python, we can use file.truncate() function.
Pass the desired size (integer value) as argument to truncate() function.
Example
In the following example, we will take a text file located at myfolder/sample.txt path and truncate the data in the file to a size of 25.
Original file
Python Program
import os
path_to_file = "myfolder/sample.txt"
with open(path_to_file, 'a') as file:
file.truncate(25)
print('File truncated successfully.')
CopyOutput
File truncated successfully.
with statement implicitly takes care of closing the file.
Resulting sample.txt
Summary
In this tutorial of Python Examples, we learned how to resize or truncate a text file using truncate() function, with the help of example programs.