John Salerno wrote: > What is the best way of altering something (in my case, a file) while > you are iterating over it? I've tried this before by accident and got an > error, naturally. > > I'm trying to read the lines of a file and remove all the blank ones. > One solution I tried is to open the file and use readlines(), then copy > that list into another variable, but this doesn't seem very efficient to > have two variables representing the file. > > Perhaps there's also some better to do it than this, including using > readlines(), but I'm most interested in just how you edit something as > you are iterating with it. > > Thanks.
Slightly new question as well. here's my code: phonelist = open('file').readlines() new_phonelist = phonelist for line in phonelist: if line == '\n': new_phonelist.remove(line) import pprint pprint.pprint(new_phonelist) But I notice that there are still several lines that print out as '\n', so why doesn't it work for all lines? -- http://mail.python.org/mailman/listinfo/python-list