Close File on Python error?

Uhm, when my script crashes (happens a lot, I’m a noob), Sometimes a filehandle does not get closed! Took me ages to find out.
Is there any way of “try/catch” or something?
Or should I store the output file in a string and flush to a file in the end, only? Might be quite memory consuming, though.

There is indeed a “try/catch” trick:

    f = file("blah","w")

Note that this is not bulletproof (i.e. if the opening of the file fails you’ll still get an exception) and it will mask all exceptions thrown by your code, so this will make debugging more difficult. But it should get you going. See

It seems try:, finally: does the job.
Thx a lot.