Open the destination with x
mode, which fails if the file already exists.
def safe_copy(srcfile, destfile):
with open(srcfile, "rb") as src, open(destfile, "wxb") as dest:
dest.write(src.read())
Opening destfile
will raise FileExistsError
. See What does python3 open "x" mode do?