Search code examples
pythonfwrite

Restore original file in case of an error


I need to write data to a file and overwrite it if file exists. In case of an error my code should catch an exception and restore original file (if applicable)

How can I restore file? Should I read original one and put content i.e. in a list and then in case of an exception just write this list to a file?

Are there any other options? Many thanks if anyone can provide some kind of an example

Cheers


Solution

  • The code below will make a copy of the original file and set a flag indicating if it existed before or not. Do you code in the try and if it makes it to the end it will set the worked flag to True and your are go to go otherwise, it will never get there, the exception will still be raised but the finally will clean up and replace the file if it had existed in the first place.

    import os
    import shutil
    
    if os.path.isfile(original_file):
        shutil.copy2(original_file, 'temp' + original_file)
        prev_existed = True
    else:
        prev_existed = False
    
    worked = False    
    try:
        with open(original_file, 'w') as f:
            ## your code
    
        worked = True
    except:
        raise        
    finally:
        if not worked and prev_existed:
            shutil.copy2('temp' + original_file, original_file)