file tell in a for-loop

Justin Ezequiel justin.mailinglists at gmail.com
Wed Nov 19 01:11:33 CET 2008


On Nov 19, 7:00 am, Magdoll <magd... at gmail.com> wrote:
> I was trying to map various locations in a file to a dictionary. At
> first I read through the file using a for-loop, but tell() gave back
> weird results, so I switched to while, then it worked.
>
> The for-loop version was something like:
>                 d = {}
>                 for line in f:
>                          if line.startswith('>'): d[line] = f.tell()
>
> And the while version was:
>                 d = {}
>                 while 1:
>                         line = f.readline()
>                         if len(line) == 0: break
>                         if line.startswith('>'): d[line] = f.tell()
>
> In the for-loop version, f.tell() would sometimes return the same
> result multiple times consecutively, even though the for-loop
> apparently progressed the file descriptor. I don't have a clue why
> this happened, but I switched to while loop and then it worked.
>
> Does anyone have any ideas as to why this is so?
>
> Thanks,
> Magdoll

got bitten by that too a while back
the for line in f reads ahead so your f.tell would not be the position
of the end of the line
had to use a while True loop instead also





More information about the Python-list mailing list