truncate()方法截断该文件的大小。如果可选的尺寸参数存在,该文件被截断(最多)的大小。
大小默认为当前位置。当前文件位置不改变。注意,如果一个指定的大小超过了文件的当前大小,其结果是依赖于平台。
注意:此方法不会在当文件工作在只读模式打开。
语法
以下是truncate()方法的语法:
立即学习“Python免费学习笔记(深入)”;
fileObject.truncate( [ size ])
立即学习“Python免费学习笔记(深入)”;
参数
size -- 如果可选参数存在,文件被截断(最多)的大小。
返回值
此方法不返回任何值。
例子
下面的例子显示 truncate()方法的使用。
立即学习“Python免费学习笔记(深入)”;
#!/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()
立即学习“Python免费学习笔记(深入)”;
当我们运行上面的程序,它会产生以下结果:
立即学习“Python免费学习笔记(深入)”;
Name of the file: foo.txt Read Line: This is 1st line Read Line:
立即学习“Python免费学习笔记(深入)”;
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号