an ugly file-reading pattern

Robin Munn rmunn at pobox.com
Mon Apr 14 10:22:25 EDT 2003


Avner Ben <avner at skilldesign.com> wrote:
> "Robin Munn" <rmunn at pobox.com> wrote in message
> news:slrnb9h7u4.it3.rmunn at localhost.localdomain...
>> Skip Montanaro <skip at pobox.com> wrote:
>> > Recent versions of Python (2.2 and later) allow this:
>> >
>> >     file = file("somefile")
>> >     for line in file:
>> >         process(line)
>>
>> Ewww! Don't *do* that! You just shadowed the "file" builtin. Use a
>> different name for your file object -- I prefer "input_file":
>>
>>     input_file = file("somefile")
>>     for line in input_file:
>>         process(line)
> 
> I have tried this shortcut and it works! (This gets rid of naming problem
> for good.)

I must have been dealing with too much spam recently: when I saw "I have
tried this and it works," I thought the next thing I was going to see
would be instructions for sending $5 to these five addresses... :-)

> 
> for line in file('/dir/filename.ext'):
>          print line
> 
> The only problem with this solution is that it leaves the timing of closing
> the file undefined. But then, neither of you guys have closed the file
> explicitly either!

You're right, I didn't close the file explicitly. But explicit is better
than implicit, so IMHO it's better to give a name to the file object so
that you can close it explicitly:

    input_file = file("somefile")
    for line in input_file:
        process(line)
    input_file.close()

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list