python - Why can't I write() multiple times on an open file? -
i trying delete words open file loop. each loop open file , remove line file , rewrite content file. finally, want generate contents original file.
the problem after loop, file not overwrote. remove 1 of words dictionary. seems when open file each iteration of loop, content of file not being updated each loop. please advise how handle file open/close in condition.
my code:
# want delete line contains pair dictionary. # example, if line contains "can_option" , "17", delete line. dictionary = {"can_optin" : "17", "appprevaddrstreet": "33"} fname = "test.txt" infile = open(fname, 'r') data = infile.readlines() infile.close() def readline(keyword, data, infile): line in data: linenumber = line.rsplit(none, 1)[-1] # line contains "can_option" or "apppreaddrstreet", # not write line file. if keyword[0] in line , linenumber == keyword[1]: print "removed: %s" % line else: infile.write(line) # start delete line here. key in dictionary.keys(): infile= open(fname, 'w') # write contents same file again , again until # loop ends. keyword = [key, dictionary[key]] # keyword list contain ["con_option", "17"] readline(keyword, data, infile) infile.close()
because not reading file. reading lines , saving in data
variable , reading data
, not written file -
dictionary = {"can_optin" : "17", "appprevaddrstreet": "33"} fname = "test.txt" infile = open(fname, 'r') data = infile.readlines() infile.close()
to read current lines have read after writing file -
dictionary = {"can_optin" : "17", "appprevaddrstreet": "33"} fname = "test.txt" def readline(keyword, data, infile): line in data: linenumber = line.rsplit(none, 1)[-1] # line contains "can_option" or "apppreaddrstreet", # not write line file. if keyword[0] in line , linenumber == keyword[1]: print "removed: %s" % line else: infile.write(line) # start delete line here. key in dictionary.keys(): infile= open(fname, 'r+') # open in read/write mode data = infile.readlines() # read again , updated data [...] keyword = [key, dictionary[key]] [...] readline(keyword, data, infile) infile.close()
Comments
Post a Comment