File not closed on exception

Ulrich Eckhardt eckhardt at
Tue Oct 20 13:26:03 CEST 2009

arve.knudsen at wrote:
> On Oct 19, 3:48 pm, Ethan Furman <et... at> wrote:
>> arve.knud... at wrote:
>>> def create():
>>>     f = file("tmp", "w")
>>>     raise Exception
>>> try:
>>>     create() 
>>> finally:
>>>     os.remove("tmp")
>> When an exception is raised, the entire stack frame at that location
>> (which includes local vars) is saved in the exception traceback.  [...] 
>> this is better:
>> def create():
>>     f = file("tmp", "w")
>>     try:
>>         do_stuff_that_raises_exception
>>     finally:
>>         os.remove("tmp")
> Why should this work? If I replace "do_stuff_that_raises_exception"
> with "raise Exception", it fails in the same way, since the file is
> open. Maybe you forgot "f.close()"?

I was puzzled by the same, but too lazy to try or ask. Anyhow, I think that
if you replaced the 'os.remove("tmp")' with 'f.close()', then the calling
function can remain the same as you wrote. This is basically the same as
when using the new-style "with", as mentioned by Gabriel.


Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

More information about the Python-list mailing list