Python 3 – File Truncate() Method
In Python, the truncate()
method is used to truncate the size of a file. Truncating a file means to shorten its length without deleting any data. The truncate()
method is only available for writable files.
Syntax
The syntax of the truncate()
method is as follows:
file.truncate(size)
Here, file
is the file object that is being truncated, and size
is the number of bytes for the new file size. If the parameter size
is not specified, the file will be truncated to position zero.
Example
Let’s see an example of how to use the truncate()
method in Python:
file = open("example.txt", "r+")
file.truncate(10)
file.close()
In this example, we first open a file called “example.txt” in read and write mode using the r+
mode. Then, we use the truncate()
method to truncate the file to 10 bytes. Finally, we close the file using the close()
method.
Output
After running the above code, the “example.txt” file would contain only the first 10 bytes of its original content.
Auto-Detection of File Content
Python’s io
module comes with an auto-detecting text file wrapper called TextIOWrapper
, which automagically detects the necessary encoding of text files. It works with practically all text files.
import io
with io.open('example.txt', 'r', encoding='utf-8') as f:
text = f.read()
print(text)
Conclusion
The truncate()
method in Python is an excellent way to shorten the length of a file without deleting any data. It is simple to use and can be implemented in any Python script with ease. Remember always to keep a backup of your files before truncating them, as there is no way to recover the lost data.