Warning about "for line in file:"

Brian Kelley bkelley at wi.mit.edu
Tue Feb 19 10:04:19 EST 2002


John Machin wrote:

> Brian Kelley <bkelley at wi.mit.edu> wrote in message news:<3C6D73DE.3090201 at wi.mit.edu>...
> [snip]
> 
>>The behavior that I would expect is exemplified in the following correct 
>>example that actually prints out all lines of a file.
>>
> 
> Correct? Does "a file" mean a particular file with 11 or fewer lines?
> It certainly doesn't work in generality for larger files:
> 
> C:\junk>cat iter_titter.py
> fsim = ["Line " + str(x) for x in range(20)]
> count = 0
> iterator = iter(fsim)
> for line in iterator:
>      if count > 10: break
>      print line
>      count = count + 1
> for line in iterator:
>      print line
> 


This is just a bug in the codingm you need to move the break statement 
after the "print line" otherwise the last iteration will not be seen.

fsim = ["Line " + str(x) for x in range(20)]
count = 0
iterator = iter(fsim)
for line in iterator:
      print line
      count = count + 1
      if count > 10: break

for line in iterator:
      print line


> C:\junk>python iter_titter.py
Line 0
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Line 11
Line 12
Line 13
Line 14
Line 15
Line 16
Line 17
Line 18
Line 19




More information about the Python-list mailing list