altering an object as you iterate over it?

John Salerno johnjsal at NOSPAMgmail.com
Fri May 19 15:11:57 EDT 2006


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.



More information about the Python-list mailing list