[Tutor] Trying to enter text from a file to a Dictionary

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jan 27 06:30:03 CET 2006

>   I tried :
>   for line in f:
>       gloss[line] = f.readline()

This should have worked, but there's one problem.  Whenever we're doing
something like:

    for line in f:

there can be some interference between the iteration and any readline()
in the body of the loop.  For efficiency reasons, the iterator's allowed
to march through the file ahead several lines at with an internal buffer.
This means our position in the file might be further along than we might
realize, and that means that readline() will give nonsensical results.

So we're getting caught by a low-level detail.  We should try to avoid
using both the for loop and readline() on the same file. Here's one way we
can avoid the problem:

    while True:
        word = f.readline()
        defn = f.readline()
        if not word or not defn:

Does this make sense?

More information about the Tutor mailing list