Python3 file.truncate()方法

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

size 默认为当前位置。当前文件位置不改变。请注意,如果指定的大小超出文件的当前大小,其结果是依赖于平台的。

注:在以只读方式打开此方法不会工作。

语法

下面是 truncate() 方法的语法 -
fileObject.truncate( [ size ])

参数

  • size -- 如果这个可选参数存在,文件被截断(最多)为这个大小(size)。

返回值

此方法不返回任何值。

示例

下面的示例显示 truncate() 方法的使用。
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
#!/usr/bin/python3

fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)

line = fo.readline()
print ("Read Line: %s" % (line))

fo.truncate()
line = fo.readlines()
print ("Read Line: %s" % (line))

# Close opened file
fo.close()
当我们运行上面的程序,会产生以下结果 -
Name of the file:  foo.txt
Read Line: This is 1s
Read Line: []

上一篇: Python3模块 下一篇: Python3文件方法