为什么我不能在打开的文件上多次写()?

时间:2015-06-18 23:56:37

标签: python

我试图用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()

2 个答案:

答案 0 :(得分:1)

因为您没有从文件中读取。您正在阅读所有行并保存在data变量中,然后仅从data读取,而不是从书面文件中读取 -

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

要读取写入文件后必须阅读的当前行 -

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()

答案 1 :(得分:0)

  

每个循环都没有更新文件内容

因为您只读取了一次数据,位于文件顶部

data = infile.readlines()

如果您希望每个循环都读取该文件的最新副本,则需要从循环内的文件中读取。