File not closed on exception

arve.knudsen at gmail.com arve.knudsen at gmail.com
Mon Oct 19 07:45:49 EDT 2009


Hi

I thought that file objects were supposed to be garbage-collected and
automatically closed once they go out of scope, 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, 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?

Thanks!
Arve



More information about the Python-list mailing list