"for line in fd" twice
Peter Hansen
peter at engcorp.com
Tue Jun 3 11:50:16 EDT 2003
"cqx": please don't top-post!
"cqx.purple.gold" wrote:
> Thomas Güttler <guettler at thomas-guettler.de> writes:
>
> > the following does not work:
> >
> > """
> > fd=open(file)
> > for line in fd:
> > if line.startswith("mymark"):
> > break
>
> # seek backwards the length(line)
>
> > for line in fd:
> > #Read lines after "mymark"
> > ....
> > fd.close()
> > """
>
> You probably need to rewind the file using 'seek'.
I don't think he wants to go back to the beginning, although it
was a little unclear. I think he wants to be able to continue
from where he left off...
Since with .readlines() the fd object maintains its state,
presumably if there is a similar approach using the implicit
iterator that is produced when you do "for line in fd" you
would be able to use that.
I doubt you can do it with the implicit iterator, however, since
the reference to it would be lost after you exit the for block,
so why not try an *explicit* iterator:
fiter = iter(open(file))
for line in fiter:
if line. blah blah: break
for line in fiter:
if line blah blah: break
This seems to work.
-Peter
More information about the Python-list
mailing list