为什么shutil.copytree不会将树从源复制到目标?

时间:2015-07-10 16:06:58

标签: python exception shutil

我有一个功能:

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)

为什么失败并输出:

Directory not copied. Error: [Errno 17] File exists: '[2]'

我的source目录与files /目录一起存在。我的destination 文件夹存在,但是当我运行此文件时,不会复制任何文件并且它会点击我的else语句。

我还尝试将这两个文件夹的权限设置为chmod 777,以避免出现unix-permission错误,但这也没有解决问题。

非常感谢任何帮助。谢谢。

2 个答案:

答案 0 :(得分:3)

我感谢大家帮助我,显然我找到了一种适用于我的情况的方法,并在下面发布,以防有​​人在某一天帮助解决这个问题(并且不花几个小时试图获得它工作) - 享受:

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)

答案 1 :(得分:0)

copytree的shutil文档说

  

递归复制以src为根的整个目录树。目标目录(由dst命名)必须不存在;它将被创建以及缺少父目录。使用copystat()复制目录的权限和时间,使用shutil.copy2()复制单个文件。

使用copytree时,需要确保src存在且dst不存在。即使顶级目录不包含任何内容,copytree也不会工作,因为它不希望在dst处有任何内容,并且将自己创建顶级目录。