File not closed on exception

Grant Edwards invalid at invalid.invalid
Mon Oct 19 16:14:45 CEST 2009

On 2009-10-19, arve.knudsen at <arve.knudsen at> wrote:

> I thought that file objects were supposed to be
> garbage-collected and automatically closed once they go out of
> scope,

At some point after they go out of scope, they will be.
Eventually.  Exactly when is an implementation detail.

> at least that's what I've been told by more merited Python
> programmers. I'm also quite sure that this is quite a common
> assumption in various programs,

If your program relies on the assumption that some particular
object will be garbage-collected between points A and B, then
that's a bug in your program.  If you depend on the fact that
some object has been delted, then "del" it.  If you depend on
the fact that a file is closed, then close it.

> at least given what opensource code I've seen in my time.
> However, the following script doesn't work on Windows, since
> the file is still open when I try to remove it:
> import os.path
> def create():
>     f = file("tmp", "w")
>     raise Exception
> try: create()
> finally:
>     os.remove("tmp")
> So, what's the deal exactly, is the file supposed to be garbage-
> collected (and closed) at the end of create?

Nothing is "supposed" to be garbage-collected.  An object _may_
be garbage collected after some point.


More information about the Python-list mailing list