2015-06-18 72 views
-1

我想從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() 
+0

你想做什麼? (重新)用'w'(創建和寫入文件)訪問來打開'infile',但是隻有'readline()'被使用。這不會寫入任何內容,也不會讀取任何內容,因爲該文件始終處於eof。 – wallyk

回答

1

因爲你不是從文件中讀取。您正在閱讀的所有線路,並在data變量保存,然後只從data閱讀它,而不是書面文件 -

dictionary = {"can_optin" : "17", "appPrevAddrStreet": "33"} 
fname = "test.txt" 

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, 'r+') # open in read/write mode 
    data = infile.readlines() # read again and get updated data 
    [...] 
    keyword = [key, dictionary[key]] 
    [...] 
    readline(keyword, data, infile) 
    infile.close() 
-

dictionary = {"can_optin" : "17", "appPrevAddrStreet": "33"} 
fname = "test.txt" 
infile = open(fname, 'r') 
data = infile.readlines() 
infile.close() 

要寫入文件後讀取你要讀電流線

0

文件的內容沒有被更新爲每個循環

因爲你只讀取一次數據,在日文件

data = infile.readlines() 

如果希望每個循環讀取最新的文件副本電子頂部,則需要從循環內的文件中讀取。

相關問題