我想對檔案中的某些行進行一些修改并覆寫檔案。我不想用更改創建一個新檔案,并且由于檔案很大(數百 MB),我不想在記憶體中一次讀取它。
datfile = 'C:/some_path/text.txt'
with open(datfile) as file:
for line in file:
if line.split()[0] == 'TABLE':
# if this is true, I want to change the second word of the line
# something like: line.split()[1] = 'new'
請注意,問題的一個重要部分是檔案很大。站點上有幾種解決方案可以解決類似的問題,但沒有考慮檔案的大小。
有沒有辦法在python中做到這一點?
uj5u.com熱心網友回復:
無論python如何,您都無法在不重寫檔案的其余部分的情況下替換檔案的一部分的內容。檔案的每個位元組都位于磁盤或閃存上的固定位置。如果要在檔案中插入比它替換的文本短或長的文本,則需要移動檔案的其余部分。如果您的替換文本比原始文本長,您可能需要撰寫一個新檔案以避免覆寫資料。
考慮到檔案 I/O 的作業方式以及您已經對檔案執行的操作,創建新檔案不會像您想象的那么大。您已經在逐行閱讀整個檔案并決議內容。對替換資料進行緩沖寫入不會那么昂貴。
from tempfile import NamedTemporaryFile
from os import remove, rename
from os.path import dirname
datfile = 'C:/some_path/text.txt'
try:
with open(datfile) as file, NamedTemporaryFile(mode='wt', dir=dirname(datfile), delete=False) as output:
tname = output.name
for line in file:
if line.startswith('TABLE'):
ls = line.split()
ls[1] = 'new'
line = ls.join(' ') '\n'
output.write(line)
except:
remove(tname)
else:
rename(tname, datfile)
傳遞dir=dirname(datfile)到NamedTemporaryFile應該保證rename在大多數情況下最終不必將檔案從一個磁盤復制到另一個磁盤。delete=False如果操作成功,使用允許您進行重命名。如果出現任何問題,臨時檔案將按名稱洗掉,否則將重命名為原始檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/341336.html
