Overview
The Python file truncate () method is used to truncate the file and return the truncated byte length.
If the length is specified, the specified length is truncated from the beginning of the file, the remainder is deleted, and if the length is not specified, it is truncated from the beginning of the file to the current location and the remainder is deleted.
Grammar
The truncate () method syntax is as follows:
Fileobject.truncate ([size])
Parameters
return value
The method has no return value.
Instance
The following example demonstrates the use of the Truncate () method:
The contents of the file Runoob.txt are as follows:
1:www.runoob.com2:www.runoob.com3:www.runoob.com4:www.runoob.com5:www.runoob.com
To iterate through the contents of a file:
#!/usr/bin/python3fo = open ("Runoob.txt", "r+", encoding= "Utf-8") # print ("File name:", Fo.name) Fo.seek (+) fo.truncate () # Removed everything from the 36th byte Fo.seek (0) line = Fo.readlines () print ("Read row:%s"% (lines)) Fo.truncate (10) # Intercept 10 bytes fo.seek (0) str = Fo.read () print ("Read data:%s"% (str)) # Close file Fo.close ()
The result of the above example output is:
File name: runoob.txt Read line: [' 1:www.runoob.com\n ', ' 2:www.runoob.com\n '] read data: 1:www.runo
Python file Truncate () method