python truncate是什么
发布时间:2024-08-21 22:17:23

1、说明
截断文件的第一行首字符,截断文件为n个字符;无n表示从当前位置切断;截断后,删除n背面的所有字符。
2、语法
fileObject.truncate([size])
3、参数
size,可选的,如果存在,文件截断为 size 字节。
4、返回值
该方法没有返回值。
5、实例
#!/usr/bin/python
#Openafile
fo=open("foo.txt","rw+")
print"Nameofthefile:",fo.name
#Asumingfilehasfollowinglines
#Thisisis1stline
#Thisisis2ndline
#Thisisis3rdline
#Thisisis4thline
#Thisisis5thline
line=fo.readline()
print"ReadLine:%s"%(line)
#Nowtruncateremainingfile.
fo.truncate()
#Trytoreadfilenow
line=fo.readline()
print"ReadLine:%s"%(line)
#Closeopendfile
fo.close()当我们操作上述程序时,它会产生以下结果:
Nameofthefile:foo.txt ReadLine:Thisis1stline ReadLine:
以上是python 介绍truncate方法,常用于切割文件,可以先对这种方法进行一次练习。更多Python学习指导:python基础教程
(推荐操作系统:windows7系统Python 3.9.1,DELL G3电脑。)
下一篇 python idle 是什么
