file iterator - what happens here?
Terry Reedy
tjreedy at udel.edu
Fri May 16 13:05:34 EDT 2003
"Helmut Jarausch" <jarausch at skynet.be> wrote in message
news:3ec4a51f$0$11146$ba620e4c at reader0.news.skynet.be...
> Hi,
>
> Python's behaviour on the following code snippet
> puzzles me
>
> cmd_input= open('Tree.inp','r')
> for line in cmd_input:
> while line.startswith('%') : # skip comment lines
> print "!!!",line
> line= cmd_input.readline()
> print "===",line,"<<<"
> if not line: break
In general, one should not modify the iterable being iterated over by
a for statement within the for loop, certainly not the
still-to-be-iterated-over part. Another example that does not work
right: deleting items in a list when iterating from front to back.
> So, obviously the line 'line= cmd_input.readline()'
> disturbs the for iterator completely.
> Is that a feature?
It is a fact to take cognizance of.
Terry J. Reedy
More information about the Python-list
mailing list