Safely renaming a file without overwriting

Diez B. Roggisch deets at
Sat Oct 28 16:48:37 CEST 2006

Wolfgang Draxinger schrieb:
> Steven D'Aprano wrote:
>> 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?
> 1: Open the file with
> 2: Lock the file exclusively -> no other process can now access
> it.
> 3: Use rename to rename the file; this causes a file system level
> implicit unlink of the old file (it dissappears from the file
> system) but the opening process can still access it.
> 4: close the file -> the lock is removed and the rename
> finalized.

Where does that help for new files? The OP was right in assuming that a 
race condition could occur when he tests for a file & then tries to 
create it, as in the meantime it could have been created.


More information about the Python-list mailing list