Rename file without overwriting existing files

Wolfgang Maier wolfgang.maier at
Mon Jan 30 06:24:58 EST 2017

On 01/30/2017 03:49 AM, Steve D'Aprano 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?

There is a rather extensive discussion of this problem (with no good 
cross-platform solution if I remember correctly):

which is related to


More information about the Python-list mailing list