Pythonic way of reading a textfile line by line without throwing an exception

Asun Friere afriere at yahoo.co.uk
Tue Aug 28 22:22:39 EDT 2007


On Aug 29, 9:49 am, "Deivys Ramirez" <deivys.rami... at gmail.com> wrote:

> What's the "pythonic" way of reading a text file, line by line,
> without throwing an exception when there's nothing to be read?
>
> I've been trying to map my while(!eof(fp)) mindset to the file object
> Python gives me when I call open() but have had no good results.

As the previous posts have indicated the idiomatic (and highly
readable) way to read a file is simply to iterate across it.  Just in
case you are ever in the position of having to use .readline()
directly, you might want to note that this method returns empty lines
as '\n' (go figure) and the EOF simply as ''.  So you test of EOF
using 'if not line :' rather than anything like 'if eof :'
Historically, ie. before file objects were iterables, you would have
written something like this:

fobj = open('foo.txt')
while 1 :
    line = fobj.readline()
    if not line :
        break
    #do stuff to line
fobj.close()

Obviously iterating 'for line in fobj : ' is neater.




More information about the Python-list mailing list