Copy file, but don’t overwrite, no problem with TOCTTOU in Python

I know that if I want to copy a file in Python, but not overwrite it, I can use this code:

if os.path.exists(dest): raise Exception("Destination file exists!") else: shutil.copy2(src, dest) 

But the state of the world can change between the moment I call os.path.exists and the time I call copy2 . Is there a more preferred way of copying without overwriting, presumably where the copy operation will throw an exception if the destination already exists?

+6
source share
1 answer

You can use the lower level os.open and then os.fdopen to copy the file:

 import os import shutil # Open the file and raise an exception if it exists fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY) # Copy the file and automatically close files at the end with os.fdopen(fd) as f: with open(src_filename) as sf: shutil.copyfileobj(sf, f) 
+7
source

Source: https://habr.com/ru/post/987886/


All Articles