Safely renaming a file without overwriting

Steven D'Aprano steve at
Sat Oct 28 12:13:33 CEST 2006

I want to rename a file, but only if the destination file name doesn't
already exist.

I can do this:

if os.path.exists(dest):
    # skip file, raise an exception, make a backup...
    os.rename(src, dest)

But on a multi-user system, it is possible that dest is created in the
time period between checking if it exists and attempting the rename.

Is there any way to prevent this? Or do I just try to keep the check and
the rename as close together as possible, minimizing the chances and
hoping for the best?


More information about the Python-list mailing list