Why is shutil.copytree not copying tree from source to destination?
Solution 1
I thank you all for trying to help me, evidentially I found a way that works for my situation and am posting it below in case it will help someone out some day to fix this issue (and not spend several hours trying to get it to work) - Enjoy:
try:
#if path already exists, remove it before copying with copytree()
if os.path.exists(dst):
shutil.rmtree(dst)
shutil.copytree(src, dst)
except OSError as e:
# If the error was caused because the source wasn't a directory
if e.errno == errno.ENOTDIR:
shutil.copy(source_dir_prompt, destination_dir_prompt)
else:
print('Directory not copied. Error: %s' % e)
Solution 2
The shutil docs for copytree say
Recursively copy an entire directory tree rooted at src. The destination directory, named by dst, must not already exist; it will be created as well as missing parent directories. Permissions and times of directories are copied with copystat(), individual files are copied using shutil.copy2().
When using copytree, you need to ensure that src exists and dst does not exist. Even if the top level directory contains nothing, copytree won't work because it expects nothing to be at dst and will create the top level directory itself.
CodeTalk
Updated on July 11, 2020Comments
-
CodeTalk almost 4 years
I have a function:
def path_clone( source_dir_prompt, destination_dir_prompt) : try: shutil.copytree(source_dir_prompt, destination_dir_prompt) print("Potentially copied?") except OSError as e: # If the error was caused because the source wasn't a directory if e.errno == errno.ENOTDIR: shutil.copy(source_dir_prompt, destination_dir_prompt) else: print('Directory not copied. Error: %s' % e)
Why is it failing and outputting :
Directory not copied. Error: [Errno 17] File exists: '[2]'
My
source
directory exists with files/directory. Mydestination
folder exists but when i run this, no files are copied and it hits myelse
statement.I tried also to set permissions on both folders to
chmod 777
to avoid unix-permission errors, but this didnt solve the issue either.Any help is greatly appreciated. Thank you.
-
Padraic Cunningham almost 9 yearswhat do you want to happen of the directory exists?
-
CodeTalk almost 9 years@PadraicCunningham - Basically overwrite the files.
-
-
CodeTalk almost 9 yearsStill getting the same error...after removing the destination directory.
-
ishaan arora over 4 yearsToday is that day :). Thanks this helped a lot!!
-
Michael Behrens over 3 yearsI see that in this example that the copytree function is only invoked if the path exists. You may want to move that command out of the if-statement block so that it is always invoked.