In this article, let's look at the python
truncatemethod, before entering the article we may not know
Truncate usageWhat, but in this article we will use
Truncate statement InstanceTo let you know about the Truncate method in today's article.
Overview
The truncate () method is used to truncate a file, and if an optional parameter size is specified, the truncated file is a size character. If size is not specified, it is truncated from the current position, and all characters after the size are deleted after truncation.
Grammar
The truncate () method syntax is as follows:
Fileobject.truncate ([size])
Parameters
Size--optional, if present, the file is truncated to a size byte.
(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/python#-*-coding:utf-8-*-# Open File fo = open ("Runoob.txt", "r+") print "file name:", Fo.nameline = Fo.readline () prin T "read first row:%s"% (line) # truncate the remaining string fo.truncate () # Try to read the data again. Line = Fo.readline () print "Read data:%s"% (line) # Close file Fo.close ()
The result of the above example output is:
The file name is: Runoob.txt reads the first line: 1:www.runoob.com reads the data:
The following instance intercepts the 10 bytes of a runoob.txt file:
#!/usr/bin/python#-*-coding:utf-8-*-# Open File fo = open ("Runoob.txt", "r+") print "file name:", fo.name# intercept 10 bytes fo.truncate (10) 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 data: 1:www.runo
In this article, we explain what is the truncate () method, do not understand the words can be hands-on to try, after all, hands-on practice is the best way to verify the learning. Finally, I hope that this article will give you a little help in learning about Python.
For more information, please visit the PHP Chinese Web Python tutorial section.