file tell in a for-loop

Magdoll magdoll at gmail.com
Tue Nov 18 18:00:14 EST 2008


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



More information about the Python-list mailing list