Python - File truncate() Method
The Python file truncate() method is used to truncate the file's size. This methods has one optional parameter which can be used to specify the size of the file in bytes after the truncate.
Example: truncate a file in Python
In the below example, Python file truncate() method is used to truncate a file called MyFile. The file is opened in the append mode using append mode.
MyFile = open("python_test.txt", "a") #Assuming the file contains #This is line 1 content. #This is line 2 content. #This is line 3 content. #file is truncated to 30 byte size MyFile.truncate(30) MyFile.close() #content of the file after truncate MyFile = open("python_test.txt", "r") print(MyFile.read()) MyFile.close()
The output of the above code will be:
This is line 1 content. This
❮ Python File Handling Methods