递归文件复制到子目录

3 投票
5 回答
5135 浏览
提问于 2025-04-16 07:52

我想把当前文件夹里的所有文件和文件夹复制到一个子文件夹里。有什么好的方法吗?我试过下面这段代码,但如果目标文件夹已经存在,它就会失败。

def copy(d=os.path.curdir):
    dest = "t"
    for i in os.listdir(d):
        if os.path.isdir(i):
            shutil.copytree(i, dest)
        else:
            shutil.copy(i, dest)

我觉得这个任务可以用更简单、更好的方法来完成。我该怎么做呢?

5 个回答

1

为了补充mamnun的回答,

如果你想直接使用操作系统的命令,我建议你使用cp -r,因为你似乎想要对文件夹进行递归复制。

1

可以查看这个链接中的代码:http://docs.python.org/library/shutil.html,然后稍微修改一下,比如在 os.makedirs(dst) 周围加点东西。

2

我在Python上是绝对不会这样做的,但我想到了一种解决方案。虽然看起来不简单,但应该是可行的,并且可以简化(我还没检查过,抱歉,现在没有电脑)。

def copyDirectoryTree(directory, destination, preserveSymlinks=True):
  for entry in os.listdir(directory):
    entryPath = os.path.join(directory, entry)
    if os.path.isdir(entryPath):
      entrydest = os.path.join(destination, entry)
      if os.path.exists(entrydest):
        if not os.path.isdir(entrydest):
          raise IOError("Failed to copy thee, the destination for the `" + entryPath + "' directory exists and is not a directory")
        copyDirectoryTree(entrypath, entrydest, preserveSymlinks)
      else:
        shutil.copytree(entrypath, entrydest, preserveSymlinks)
    else: #symlinks and files
      if preserveSymlinks:
        shutil.copy(entryPath, directory)
      else:
        shutil.copy(os.path.realpath(entryPath), directory)

撰写回答