Q on explicitly calling file.close

David C Ullrich dullrich at sprynet.com
Wed Sep 9 22:18:46 CEST 2009

On Sat, 05 Sep 2009 23:41:08 +0000, Steven D'Aprano wrote:

> On Sat, 05 Sep 2009 16:14:02 +0000, kj wrote:
>> Finally, I was under the impression that Python closed filehandles
>> automatically when they were garbage-collected.
> (3) For quick and dirty scripts, or programs that only use one or two
> files, relying on the VM to close the file is sufficient (although lazy
> in my opinion *wink*)

Many years ago I read some big Python guy say something to the
effect that you didn't "need" to close files, but if you don't
it will bite you eventually.

So I learned to type "close()". Of course I wouldn't worry about
that in quick and dirty scripts. Then there was that quick and
dirty script that gradually mutated into a not-so-quick and filthy
monstrosity that a certain project depended on. Stopped working 
one day.

Me being dim, it took almost a day to find the problem... (I don't
recall how exactly an open file caused a problem, it was still just
three or four files altogether.)

These days I've actually got the syntax and spelling memorized -
I can type "close()" without needing to look it up!

> but for long-running applications using many
> files, or for debugging, you may want more control over what happens
> when.

More information about the Python-list mailing list