Checking for end of a file

CB nospam at email.com
Thu Jul 20 17:07:47 EDT 2000


Thanks, works a treat.

Colin

"Bjorn Pettersen" <bjorn at roguewave.com> wrote in message
news:39776623.5B245EF5 at roguewave.com...
> 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