file.truncate([size])
描述 (Description)
truncate()方法truncate()文件的大小。 如果存在可选的大小参数,则文件将截断为(最多)该大小。
size默认为当前位置。 当前文件位置未更改。 请注意,如果指定的size超过文件的当前大小,则结果与平台有关。
Note - 如果以只读模式打开文件,则此方法不起作用。
语法 (Syntax)
以下是truncate()方法的语法 -
fileObject.truncate( [ size ])
参数 (Parameters)
size - 如果存在此可选参数,则文件将截断为(最多)该大小。
返回值 (Return Value)
此方法不返回任何值。
例子 (Example)
以下示例显示了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: