Rename file without overwriting existing files

MRAB python at mrabarnett.plus.com
Sun Jan 29 22:45:20 EST 2017


On 2017-01-30 03:27, Chris Angelico wrote:
> On Mon, Jan 30, 2017 at 1:49 PM, Steve D'Aprano
> <steve+python at pearwood.info> wrote:
>> This code contains a Time Of Check to Time Of Use bug:
>>
>>     if os.path.exists(destination)
>>         raise ValueError('destination already exists')
>>     os.rename(oldname, destination)
>>
>>
>> In the microsecond between checking for the existence of the destination and
>> actually doing the rename, it is possible that another process may create
>> the destination, resulting in data loss.
>>
>> Apart from keeping my fingers crossed, how should I fix this TOCTOU bug?
>
> The Linux kernel (sorry, I don't know about others) provides a
> renameat2() system call that has the option of failing if the
> destination exists. However, I can't currently see any way to call
> that from CPython. Seems like an excellent feature request - another
> keyword-only argument for os.rename(), like the directory file
> descriptors.
>
On Windows it raises FileExistsError if the destination already exists.

shutil.move, on the other hand, replaces if the destination already exists.



More information about the Python-list mailing list