用 python 處理一個文本時,想要刪除其中中某一行,常規的思路是先把文件讀入內存,在內存中修改后再寫入源文件。
但如果要處理一個很大的文本,比如GB級別的文本時,這種方法不僅需要占用很大內存,而且一次性讀入內存時耗費時間,還有可能導致內存溢出。
所以,需要用另外一個思路去處理。
我們可以使用 open() 方法把需要修改的文件打開為兩個文件,然后逐行讀入內存,找到需要刪除的行時,用后面的行逐一覆蓋。實現方式見以下代碼。
1 with open('file.txt', 'r') as old_file: 2 with open('file.txt', 'r+') as new_file: 3 4 current_line = 0 5 6 # 定位到需要刪除的行 7 while current_line < (del_line - 1): 8 old_file.readline() 9 current_line += 1 10 11 # 當前光標在被刪除行的行首,記錄該位置 12 seek_point = old_file.tell() 13 14 # 設置光標位置 15 new_file.seek(seek_point, 0) 16 17 # 讀需要刪除的行,光標移到下一行行首 18 old_file.readline() 19 20 # 被刪除行的下一行讀給 next_line 21 next_line = old_file.readline() 22 23 # 連續覆蓋剩余行,后面所有行上移一行 24 while next_line: 25 new_file.write(next_line) 26 next_line = old_file.readline() 27 28 # 寫完最后一行后截斷文件,因為刪除操作,文件整體少了一行,原文件最后一行需要去掉 29 new_file.truncate()