altering an object as you iterate over it?

bruno at modulix onurb at xiludom.gro
Fri May 19 21:33:26 CEST 2006

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.

If the file is huge, this can be a problem. But you cannot modify a text
file in place anyway.

For the general case, the best way to go would probably be an iterator:

def iterfilter(fileObj):
  for line in fileObj:
    if line.strip():
      yield line

f = open(path, 'r')
for line in iterfilter(f):

Now if what you want to do is just to rewrite the file without the blank
files, you need to use a second file:

fin = open(path, 'r')
fout = open(temp, 'w')
for line in fin:
  if line.strip():

then delete path and rename temp, and you're done. And yes, this is
actually the canonical way to do this !-)

bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"

More information about the Python-list mailing list