【问题标题】:Python: copy folder content recursivelyPython:递归复制文件夹内容
【发布时间】:2014-04-27 21:11:40
【问题描述】:

我想递归地复制文件夹的内容,而不复制已经存在的文件。此外,目标文件夹已经存在并包含文件。 我尝试使用shutils.copytree(source_folder, destination_folder),但它并没有达到我想要的效果。

我希望它像这样工作:

之前:

  • source_folder
    • 子文件夹_1
      • 酒吧
    • sub_folder_2

  • 目标文件夹
    • folder_that_was_already_there
      • file2.jpeg
    • some_file.txt
    • 子文件夹_1

之后:

  • 目标文件夹
    • folder_that_was_already_there
      • file2.jpeg
    • some_file.txt
    • 子文件夹_1
      • 酒吧
    • sub_folder_2

【问题讨论】:

  • 您能否澄清一下,什么不起作用?似乎您有一些与要复制什么文件和不复制什么文件相关的特定逻辑,不要指望shutils 为您做这件事,这必须在您的代码中决定。你能给我们看一些代码吗?
  • 使用os.walk()枚举源树,os.path.exists()查看目标是否存在,os.stat()查看目标是否较旧,os.mkdir ()/shutil.copy2() 做事。
  • tdelaney 是对的。我实施它。我会尽快将其作为答案发布。

标签: python file recursion copy


【解决方案1】:

我在tdelaney的帮助下找到了答案:
source_folder 是源的路径,destination_folder 是目标的路径。

import os
import shutil

def copyrecursively(source_folder, destination_folder):
for root, dirs, files in os.walk(source_folder):
    for item in files:
        src_path = os.path.join(root, item)
        dst_path = os.path.join(destination_folder, src_path.replace(source_folder, ""))
        if os.path.exists(dst_path):
            if os.stat(src_path).st_mtime > os.stat(dst_path).st_mtime:
                shutil.copy2(src_path, dst_path)
        else:
            shutil.copy2(src_path, dst_path)
    for item in dirs:
        src_path = os.path.join(root, item)
        dst_path = os.path.join(destination_folder, src_path.replace(source_folder, ""))
        if not os.path.exists(dst_path):
            os.mkdir(dst_path)

【讨论】:

    【解决方案2】:

    你看过distutils.dir_util.copy_tree()吗? update 参数默认为0,但您似乎想要1,它只会在目标文件不存在或文件较旧时复制。在您的问题中,我没有看到copy_tree() 无法涵盖的任何要求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 2010-12-28
      • 2011-05-31
      • 2011-01-12
      • 2018-02-07
      • 2015-12-03
      相关资源
      最近更新 更多