I need to have a file deleted if not all the operations that must be done on it were successful (that is, if an exception is raised). It could have been as simple as using except:, deleting the file and then re-raising the exception, but in that case the original exception would be lost if the file cannot be deleted in the except clause for whatever arcane reason.
The best that I have been able to come up with is this:
try:
file_path = "whatever.jpg"
# do stuff with file
except:
exception_raised = True
raise
finally:
try:
if exception_raised:
os.unlink(file_path)
except:
pass
return file_path # everything OK
Does anybody know of a better, more Pythonic approach?