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)