Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is shutil.copytree not copying tree from source to destination?

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. My destination folder exists but when i run this, no files are copied and it hits my else 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.

like image 837
CodeTalk Avatar asked Jul 10 '15 16:07

CodeTalk


2 Answers

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)
like image 160
CodeTalk Avatar answered Sep 16 '22 14:09

CodeTalk


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.

like image 45
Matt Habel Avatar answered Sep 16 '22 14:09

Matt Habel