Rename file without overwriting existing files

Steve D'Aprano steve+python at pearwood.info
Sun Jan 29 21:49:43 EST 2017


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?



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list