Reputation: 135
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
Upvotes: 0
Views: 575
Reputation: 2840
One way to do it is the append the new data at the end of the existing file. If you catch an error , delete all that you appended. If no errors, delete everything that you had before appending so the new file will have only the appended data.
Create a copy of your file before starting capturing the data in a new file.
Upvotes: 1
Reputation: 1096
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)
Upvotes: 1
Reputation: 6214
Any attempt to restore on error will be fragile; what if your program can't continue or encounters another error when attempting to restore the data?
A better solution would be to not replace the original file until you know that whatever you're doing succeeded. Write whatever you need to to a temporary file, then when you're ready, replace the original with the temporary.
Upvotes: 1