Q on explicitly calling file.close
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Sep 5 19:41:08 EDT 2009
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. (In fact (3) suggests
> as much, since it does not include an implicit call to fh.close.) If so,
> the difference between (1) and (3) does not seem very big. What am I
> missing here?
(1) Python the language will close file handles, but doesn't guarantee
when. Some implementations (e.g. CPython) will close them immediately the
file object goes out of scope. Others (e.g. Jython) will close them
"eventually", which may be when the program exists.
(2) If the file object never goes out of scope, say because you've stored
a reference to it somewhere, the file will never be closed and you will
leak file handles. Since the OS only provides a finite number of them,
any program which uses large number of files is at risk of running out.
(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*) but for long-running applications using many files,
or for debugging, you may want more control over what happens when.
--
Steven
More information about the Python-list
mailing list