[Tutor] Fwd: Trying to enter text from a file to a Dictionary
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Fri Jan 27 22:21:11 CET 2006
> Here's one way we can avoid the problem:
>
> while True:
> word = f.readline()
> defn = f.readline()
> if not word or not defn:
> break
> ...
>
> Does this make sense?
>
> It does mostly...I don't see why you need the:
>
> if not word or not defn:
> break
>
> If this is so that when python iterates to the end of the file, it knows
> to stop, and if that is so, then why doesn't python know it has gotten
> to the end of the file without it being told?
Hi Ben,
Yes, that's the point: Python doesn't know when to stop. *grin*
The way we've rewritten the loop:
while True:
...
is an "infinite" loop that doesn't stop unless something in the loop's
body does something extraordinary, like "breaking" out of the loop.
Python is much dumber than we might expect.
In more detail: Python's readline() method doesn't fail when we reach the
end of a file: we actually start hitting the empty string. For example:
######
>>> import StringIO
>>> sampleTextFile = StringIO.StringIO("""This is
... a sample
... text file
... """)
>>> sampleTextFile.readline()
'This is\n'
>>> sampleTextFile.readline()
'a sample\n'
>>> sampleTextFile.readline()
'text file\n'
>>> sampleTextFile.readline()
''
>>> sampleTextFile.readline()
''
######
Notice that when we hit the end of the file, readline() still continues to
run and give us empty string values. That's why the loop above needs to
make sure it breaks out in this particular situation.
Does this make sense? Please feel free to ask questions about this.
More information about the Tutor
mailing list