File Parsing Question

Peter Otten __peter__ at
Thu Sep 13 08:03:44 CEST 2007

Am Wed, 12 Sep 2007 17:28:08 -0500 schrieb Shankarjee Krishnamoorthi:

> I would prefer to use something with seek. 

Writing Perl in any language?

> I am not able to use seek()
> with "for line in inp". Use tell and seek does not seem to do anything
> with the code. When I try to do
> for line in inp.readlines():

readlines() reads the whole file at once, so inp.tell() will give the
position at the end of the file from now on.

>     # Top of Loop
>     if not condition in line:
>             do_something
>     else:
>           for lines in inp.readlines():
>               if not condition
>                    do_something
>               else:
>                    break
>                    pos = inp.tell()
>   ---> This line has not effect in the program
> Not sure if Iam missing something very basic. Also the previous line
> needs to be used in the position I call # Top of Loop.

If you want to use seek/tell you can't iterate over the file directly

for line in inp: 
   # ...

reads ahead to make that iteration highly efficient -- so you will often
get a position further ahead than the end of the current line. 

But you can use readline() (which doesn't read ahead) in conjunction with
tell/seek; just replace all occurences of

for line in inp:
    # ...


for line in iter(inp.readline, ""):
    # ...        


More information about the Python-list mailing list