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.
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
import os path_to_file = "myfolder/sample.txt" with open(path_to_file, 'a') as file: file.truncate(25) print('File truncated successfully.')
File truncated successfully.
with statement implicitly takes care of closing the file.
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.