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檔方法