When writing scripts, I often want to perform a file copy where I do not want to overwrite any existing files. I want to copy from "src" to "dest", and if a file exists at "dest", it should throw an exception. It's straightforward to write something like (Python):
But there is a race condition here -- there is a brief window of time after the check in which if a file is created at "destfile", it will be replaced. (In the worst case, this type of window leads to a symlink race).
I wish Python solved this problem automatically, but the Python documentation explicitly says that shutil.copy and shutil.copy2 can silently overwrite the destination file if it already exists, and there is no flag to prevent this. Even worse, the behavior for overwriting existing files is different across platforms(!) So, I had to call into the operating system at a lower level. Here is my code for safer moves and copies, in both Linux and Windows:
Many tests and more file utilities like this can be found on my GitHub page here.