I have a directory with some files in it (they're mostly images with a JSON file). I want to process those files, possibly overwrite some of them and possibly create some new files from some other source. I can have an error happen at any point in this process.
How do I ensure that if an error occurs as I'm processing one of the files that I won't end up with the directory in a weird state? I want to only change the contents of the directory if everything went well.
Should I create a temporary directory with tempfile.mkdtemp
, put my code in a try
, do my update in the "temporary" directory, swap the existing directory with the temporary directory, and delete the temporary directory if it still exists in the finally
?
I'm using Python (Django).