Force Overwrite in Os.Rename

Since Python 3.3, there is now a standard cross-platform solution, os.replace:

Rename the
file or directory src to dst. If dst is a directory, OSError will be
raised. If dst exists and is a file, it will be replaced silently if
the user has permission
. The operation may fail if src and dst are on
different filesystems. If successful, the renaming will be an atomic
operation (this is a POSIX requirement).

Availability: Unix, Windows.

New in version 3.3.

However, contrary to the documentation, on Windows it’s not guaranteed to be atomic (in Python 3.4.4). That’s because internally it uses MoveFileEx on Windows, which doesn’t make such a guarantee.

Leave a Comment