Rename file without overwriting existing files

Chris Angelico rosuav at gmail.com
Sun Jan 29 22:27:08 EST 2017


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.

ChrisA


More information about the Python-list mailing list