我想從for循環打開的文件中刪除一些單詞。 每個循環我打開文件並從文件中刪除行並將內容重寫到文件。 最後,我想用原始文件生成內容。爲什麼我不能在打開的文件上多次寫入()?
問題出在for循環之後,文件沒有被覆蓋。 它只刪除字典中的一個單詞。好像當我在循環的每次迭代中打開文件時,文件的內容並未針對每個循環進行更新。 請告知如何在這種情況下處理打開/關閉文件。
我的代碼:
# I want to delete the line which contains the pair from the dictionary.
# For example, if a line contains "can_option" and "17", then I will delete the line.
dictionary = {"can_optin" : "17", "appPrevAddrStreet": "33"}
fname = "test.txt"
infile = open(fname, 'r')
data = infile.readlines()
infile.close()
def readline(keyword, data, infile):
for line in data:
lineNumber = line.rsplit(None, 1)[-1]
# line contains "can_option" or "appPreAddrStreet",
# then does not write the line to the file.
if keyword[0] in line and lineNumber == keyword[1]:
print "Removed: %s" % line
else:
infile.write(line)
# start to delete line from here.
for key in dictionary.keys():
infile= open(fname, 'w')
# write the contents to the same file again and again until
# the loop ends.
keyword = [key, dictionary[key]]
# the keyword list will contain ["con_option", "17"]
readline(keyword, data, infile)
infile.close()
你想做什麼? (重新)用'w'(創建和寫入文件)訪問來打開'infile',但是隻有'readline()'被使用。這不會寫入任何內容,也不會讀取任何內容,因爲該文件始終處於eof。 – wallyk