Checking for end of a file
Bjorn Pettersen
bjorn at roguewave.com
Thu Jul 20 16:50:43 EDT 2000
CB wrote:
>
> If I'm iterating through a text file, reading one line at a time within a
> while statement, how do I check for the end of file. I tried while
> filename.eof and filename.eof() but to no avail?
>
> Colin
The two standard idioms are:
f = open(...)
for line in f.readlines():
<do something with line>
and
while 1:
line = f.readline()
if not line: break
<do something with line>
The second one works by the fact that f.readline() returns '\n' for
empty lines and '' (the empty string, aka false) when reaching the
end-of-file.
I'm-not-even-going-to-try-to-defend-while-1'ly y'rs
-- bjorn
More information about the Python-list
mailing list