Would it be safer to write to a temporary file in the same directory and then remove and rename at the end?  With the current logic if there is a failure downstream from here then the original is lost.

BTW it seems there is no atomic `mv` to an existing file on Windows, at least from my reading of the os.rename() docs.