Python文件truncate()方法

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

截断的大小(size)默认为当前位置。 请注意,如果指定的大小(size)超过文件的当前大小,则结果与平台相关。

注 - 如果文件以只读模式打开,则此方法将无法正常工作。

语法

以下是truncate()方法的语法 -

fileObject.truncate( [ size ])

参数

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

返回值

  • 此方法不返回任何值。

示例

假设’foo.txt‘文件中包含以下行 -

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

以下示例显示了truncate()方法的用法。

#!/usr/bin/python3

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

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

pos=fo.tell()
print ("current position : ",pos)

# Close opened file
fo.close()

执行上面代码后,将得到以下结果 -

Name of the file:  foo.txt
Read Line: This is 1s
Read Line: []

上一篇: Python文件对象方法 下一篇: Python os模块方法