Python file方法truncate()截断文件的大小。如果存在可选的size参数,文件将被截断为(至多)该大小。
大小默认为当前位置。当前文件位置不变。请注意,如果指定的size超过文件的当前大小,则输出取决于平台。
注意-如果文件以只读模式打开,此方法将不起作用。
fileObject.truncate( [ size ])
size - 如果存在此可选参数,文件将被截断为(至多)该大小。
此方法不返回任何值。
以下示例显示truncate()方法的用法。
This is 1st line This is 2nd line This is 3rd line This is 4th line This is 5th line
#!/usr/bin/python # Open a file fo=open("foo.txt", "rw+") print "Name of the file: ", fo.name # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line line=fo.readline() print "Read Line: %s" % (line) # Now truncate remaining file. fo.truncate() # Try to read file now line=fo.readline() print "Read Line: %s" % (line) # Close opend file fo.close()
当无涯教程运行上面的程序时,它产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/python/file-truncate.html
来源:LearnFk无涯教程网
Name of the file: foo.txt Read Line:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)