正確的方法是先完全閱讀內容,讓您的修改,然後寫回文件。
這種方法乾淨可讀。
#first read everything
with open('file_name','r') as f:
content = f.read()
#now perform modifications
content = content.replace('foo 69','')
#now write back to the file
with open('file_name','w') as f:
f.write(content)
現在,我已經評論了一些你在你的代碼有問題:
with open('file_name','a+') as f:
for line in f:#here you are iterating through the content of the file
# at each iteration line will equal foo 69, then bar 70 and then bar 71...
# Now, there is no reason to open the file here again, I guess you opened
# it to write again, but your mode is set to `a` which will append contents
# not overwrite them
with open('contacts.txt','a+') as f:
if "foo" in line:
line.replace("foo", "") #here the modified content is lost
# because you're not storing them anywhere
編輯 - 正如在評論中提到的,如果你的文件是相當大的,你不這樣做想要閱讀所有的內容。
然後做到這一點,最好的辦法就是逐行讀取內容系並寫入內容到另一個文件中不包括你要刪除的行。
to_replace = 'foo 69\n' #note \n is neccessary here
with open('input.txt','r') as input_file:
with open('ouput.txt','w') as output:
for line in input_file:
if line!=to_replace:
output.write(line)
#Now, let's say you want to delete all the contents of the input_file
#just open it in write mode and close without doing anything
input_file = open('input_file.txt','w')
input_file.close()
# If you want to delete the entire input_file and rename output_file to
# original file_name then you can do this in case of linux OS using subprocess
subprocess.call(['mv', 'output_file.txt', 'input_file.txt'])
由於在任何時間點只有一行內容在內存中,所以這非常具有內存效率。 input_file
只是一個指向該文件的指針,迭代 - for line in input_file
不會讀取整個文件並開始逐個迭代內容。
刪除整行或只是foo? – depperm
'line'是一個字符串,調用'line.replace(「foo」,「」)''''''但實際上並不影響字符串,因爲函數沒有發生。即使這樣做,它也不會將其寫回文件。 –
@hiroprotagonist好吧我將它存儲在一個變量中並寫入文件。現在結果是相同的文本文件,但最後是「69」。 –