无涯教程-File函数 - file.truncate([size])

87 阅读1分钟

Python file方法truncate()截断文件的大小。如果存在可选的size参数,文件将被截断为(至多)该大小。

大小默认为当前位置。当前文件位置不变。请注意,如果指定的size超过文件的当前大小,则输出取决于平台。

注意-如果文件以只读模式打开,此方法将不起作用。

file.truncate([size]) - 语法

fileObject.truncate( [ size ])
  • size  -  如果存在此可选参数,文件将被截断为(至多)该大小。

file.truncate([size]) - 返回值

此方法不返回任何值。

file.truncate([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()

当无涯教程运行上面的程序时,它产生以下输出-

Name of the file:  foo.txt

Read Line:

参考链接

www.learnfk.com/python/file…