Safely renaming a file without overwriting

Chetan pandyacus.xspam at xspam.sbcglobal.net
Sat Oct 28 19:54:09 CEST 2006


Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> writes:

> 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...
>     do_something_else() 
> else:
>     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?
> 
> 
> -- 
> Steven.

The answer, unfortunately, depends on the platform. I haven't tried, but it
looks like rename() will fail on Win32 if the file already exists. On Unix, you
can use link to rename the file - which will not overwrite the file if it
exists. Then use unlink to remove the src file.

Chetan



More information about the Python-list mailing list