Python 文件 truncate() 方法用于截斷文件并返回截斷的字節(jié)長度。
指定長度的話,就從文件的開頭開始截斷指定長度,其余內(nèi)容刪除;不指定長度的話,就從文件開頭開始截斷到當前位置,其余內(nèi)容刪除。
truncate() 方法語法如下:
1 | fileObject.truncate([size]) |
size -- 可選,如果存在則文件從開頭截斷為指定字節(jié)。
該方法沒有返回值。
以下實例演示了 truncate() 方法的使用:
文件 365jz.txt 的內(nèi)容如下:
1 2 3 4 5 | 1:theartemis.cn 2:theartemis.cn 3:theartemis.cn 4:theartemis.cn 5:theartemis.cn |
循環(huán)讀取文件的內(nèi)容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #!/usr/bin/python3
fo = open("365jz.txt", "r+", encoding="utf-8") # print ("文件名: ", fo.name)
fo.seek(36) fo.truncate() # 從第36個字節(jié)以后的內(nèi)容全部刪除了 fo.seek(0,0) line = fo.readlines() print("讀取行: %s" % (line)) fo.truncate(10) # 截取10個字節(jié) fo.seek(0,0) str = fo.read() print("讀取數(shù)據(jù): %s" % (str))
# 關閉文件 fo.close() |
以上實例輸出結果為:
1 2 3 | 文件名: 365jz.txt 讀取行: ['1:theartemis.cn\n', '2:theartemis.cn\n'] 讀取數(shù)據(jù): 1:www.365j |
假設’foo.txt
‘文件中包含以下行 -
This is 1st line This is 2nd line This is 3rd line This is 4th line This is 5th lineShell
以下示例顯示了truncate()
方法的用法。
#!/usr/bin/python3fo = 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 filefo.close()Python
執(zhí)行上面代碼后,將得到以下結果 -
Name of the file: foo.txt Read Line: This is 1s Read Line: []
如對本文有疑問,請?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會為你解答?。?點擊進入論壇