-4

In a 2016 blogpost, it is claimed:

def notActuallySafeCopy(srcfile, destfile):
    if os.path.exists(destfile):
        raise IOError('destination already exists')
    
    shutil.copy(srcfile, destfile)

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.

... 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.

Is this still true? Does Python supply a way to copy a file that does not overwrite a destination file?

0

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.