Reputation: 4426
For the purpose of safely updating a file, I am writing an updated version to a temporary file and then try to overwrite the original file with it. In a shell unix script I would use mv FROM TO
for this.
With python on Linux, the functions os.rename and shutil.move perform an atomic replace operation when the target filename exists. On Windows, they fail.
The behavior can be approximated by a sequence of copy, rename and remove operations, but it cannot be guaranteed, that such a self-written replace operation is performed either finished or completely reverted.
Is it possible to get a reliable “rename and overwrite” operation on Windows?
Upvotes: 1
Views: 1443
Reputation: 4426
As of Python 3.3, the function os.replace
is available. It should provide cross-platform mv
-like semantics.
Sadly it fails when trying to move files across file systems.
Even though the documentation says, that shutil.move depends on the semantics of os.rename, it also works on Windows, and supports moving files across file-system boundaries. Sadly, I have seen cases where for some reason it still denied overwriting a file, so when possible, os.replace should be safer.
Upvotes: 2