"for line in fd" twice

Terry Reedy tjreedy at udel.edu
Tue Jun 3 21:00:55 CEST 2003

"Thomas Güttler" <guettler at thomas-guettler.de> wrote in message
news:bbiej5$9uiab$1 at ID-63505.news.dfncis.de...
> Hi!
> the following does not work:
> """
> fd=open(file)
> for line in fd:
>     if line.startswith("mymark"):
>         break
> for line in fd:
>     #Read lines after "mymark"
>     ....
> fd.close()
> """
> The second loop misses some lines.

In general, the effect of re-iterating is undefined.

In 2.2, I believe the file iterator internally uses
fd.read(large_chunk) for efficiency.  So the break tosses away the
last read-but-not-reported chunk.  2.3 may be slightly different.

> It works with the old way:
> """
> while 1:
>     line=fd.readline()
>     if not line:
>         break
> """

Now you are explicitly reading one line at a time.  Slower but more
sure for your case.

> If you mustnot call "for line in fd" twice, it would
> be nice to get an exception which reminds me about it.

There has been some debate on exactly what to do or say when.  Not
sure if 2.3 will be any different


More information about the Python-list mailing list