an ugly file-reading pattern

Robin Munn rmunn at
Tue Apr 15 17:28:31 CEST 2003

Jp Calderone <exarkun at> wrote:
> On Mon, Apr 14, 2003 at 06:53:32PM +0200, Avner Ben wrote:
>> "Robin Munn" <rmunn at> wrote in message
>> > 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()
>>     The C# language has a nice construct: using (variable = whatever) { /*
>> code */ }. The variable in the using header is guaranteed to be
>> garbage-collected at the end of the block (or so I think). Could be useful
>> here.
>   In CPython, the reference count to the file object in:
>     for line in file(...):
>         ...
>   will drop to 0 immediately after the loop, and the file will be closed at
> that point.

But the Python language spec doesn't guarantee that objects will be
garbage-collected immediately when their refcount drops to 0; and, in
fact, Jython does *not* garbage-collect zero-refcount objects
immediately. Relying on garbage-collection is not safe. For most
operations, it's safe enough (if a file stays open a bit longer than you
expected, it's probably not a big deal) but there are times when it is
important to know exactly when the file is closed; I prefer to simply
make a habit of it.

Robin Munn <rmunn at>
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838

More information about the Python-list mailing list