Python:递归复制文件夹内容

3 投票
2 回答
7313 浏览
提问于 2025-04-18 04:30

我想要把一个文件夹里的内容递归地复制到另一个文件夹,但不想复制那些已经存在的文件。而且,目标文件夹已经存在,并且里面有一些文件。

我尝试使用 shutils.copytree(source_folder, destination_folder),但是它没有达到我的要求。

我希望它能像这样工作:

复制前:

  • 源文件夹(source_folder)
    • 子文件夹1(sub_folder_1)
      • foo
      • bar
    • 子文件夹2(sub_folder_2)

  • 目标文件夹(destination_folder)
    • 已经存在的文件夹(folder_that_was_already_there)
      • file2.jpeg
    • some_file.txt
    • 子文件夹1(sub_folder_1)
      • foo

复制后:

  • 目标文件夹(destination_folder)
    • 已经存在的文件夹(folder_that_was_already_there)
      • file2.jpeg
    • some_file.txt
    • 子文件夹1(sub_folder_1)
      • foo
      • bar
    • 子文件夹2(sub_folder_2)

2 个回答

0

你有没有看过 distutils.dir_util.copy_tree() 这个函数?这个函数里的 update 参数默认是 0,但看起来你可能想要的是 1,这样的话,它只会在目标位置没有文件或者文件比较旧的时候才会复制。我在你的问题里没有看到有什么是 copy_tree() 不能解决的。

3

我在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)

撰写回答