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

Cod*_*alk 2 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)
Run Code Online (Sandbox Code Playgroud)

为什么失败并输出:

Directory not copied. Error: [Errno 17] File exists: '[2]'
Run Code Online (Sandbox Code Playgroud)

我的source目录与文件/目录一起存在。我的destination 文件夹存在,但是当我运行它时,没有文件被复制,并且命中了我的else声明。

我还尝试在两个文件夹上设置权限chmod 777以避免unix权限错误,但这也不能解决问题。

任何帮助是极大的赞赏。谢谢。

小智 12

您可以使用以下参数:

copytree(source, dest, dirs_exist_ok = True)
Run Code Online (Sandbox Code Playgroud)

这将覆盖已存在的同名数据,而不会引发错误。


Mat*_*bel 5

copytree 的 Shutil 文档说

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

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

  • 仍然得到同样的错误......删除目标目录后。 (2认同)

Cod*_*alk 5

感谢所有尝试为我提供帮助的人,很明显,我找到了一种适合我的情况的方法,并将其发布在下面,以防它有一天会帮助某人解决此问题(而不必花费数小时的时间来使它正常工作) ) - 请享用:

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)
Run Code Online (Sandbox Code Playgroud)

  • 我看到在此示例中,仅当路径存在时才会调用 copytree 函数。您可能希望将该命令移出 if 语句块,以便始终调用它。 (4认同)
  • 今天就是那一天:)。谢谢这有很大帮助! (2认同)