File not closed on exception

Ethan Furman ethan at
Mon Oct 19 15:48:33 CEST 2009

arve.knudsen at wrote:
> 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

When an exception is raised, the entire stack frame at that location 
(which includes local vars) is saved in the exception traceback.  Since 
the objects are still alive, they are not GC'ed.  That is why this is 

def create():
     f = file("tmp", "w")


More information about the Python-list mailing list