Search code examples
pythonwith-statementresource-cleanup

How to delete file created in with statement if with-block fails (python)


I have some code like this:

with open(output_path, 'w') as output_file:
    #create and write output file

Upon running this, then even if there is an error somewhere, the file has been created and is in an incomplete state .

I would like it, that if there is an exception raised (and not handled) in the with-block, then the file be deleted. What's the best way to do this?

My understanding is if I try to do it in with a (try ...) finally statement, it will happen even if there is no exception, while if I put it after an except statement, the exception will not continue to bubble up, which is what I want it to do. (I don't want to handle the exception, just delete the file before the code stops running.)


Solution

  • You can simply call raise within your except block, and it will re-raise the exception to allow the exception to bubble up. See this relevant section of python documentation.

    For your example, you could write something similar to the following:

    try:
        with open(output_path, 'w') as output_file:
            # Create and write output file.
    except:
        # Delete the file.
        # Re-raise the exception with all relevant information (message, stacktrace, etc).
        raise