【问题标题】:Why is shutil.copytree not copying tree from source to destination?为什么 shutil.copytree 不将树从源复制到目标?
【发布时间】:2015-07-10 16:06:58
【问题描述】:

我有一个函数:

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 目录与文件/目录一起存在。我的destination 文件夹 存在,但是当我运行它时,没有文件被复制并且它命中了我的else 语句。

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

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

【问题讨论】:

  • 你想对存在的目录发生什么?
  • @PadraicCunningham - 基本上覆盖文件。

标签: python exception shutil


【解决方案1】:

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

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)

【讨论】:

  • 今天就是那一天:)。谢谢这有很大帮助!
  • 我看到在这个例子中,只有当路径存在时才会调用 copytree 函数。您可能希望将该命令移出 if 语句块,以便始终调用它。
【解决方案2】:

copytree 的 shutil 文档说

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

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

【讨论】:

  • 仍然得到同样的错误...删除目标目录后。
猜你喜欢
  • 2010-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多