NEWBIE TIP: Reading a file two different ways...from ENGSOL

Alex Martelli aleaxit at yahoo.com
Sat Aug 4 03:55:28 EDT 2001


<engsol at teleport.com> wrote in message
news:3b6b720d.12189167 at news.onemain.com...
    ...
> If it's in error, please post a correction.
    ...
> def readfile(foo_name):                           # Pretty much as above
>     foo_file = open(foo_name, 'r')
>     while 1:
>         foo_line = foo_file.readline()
>         if foo_line:                              # Notice we change the
order of
>             print foo_line,                       # the IF, just because
we can
>         else:
>             break
>     foo_file.close()

It should work fine, but it's needlessly complicated.  Why not:

def readfile(foo_name):
    foo_file = open(foo_name, 'r')
    for foo_line in foo_file.xreadlines():
        print foo_line,
    foo_file.close()

if one wants to be Finalizationly Correct, or just:

    for foo_line in open(foo_name, 'r').xreadlines():
        print foo_line,

if the potential risk of having a file stay open (for reading) a
little longer than strictly necessary (in implementations that
can't guarantee finalization, such as Jython) is not an issue.


Alex






More information about the Python-list mailing list