gpt4 book ai didi

Python:递归复制文件夹内容

转载 作者:行者123 更新时间:2023-11-28 16:38:06 25 4
gpt4 key购买 nike

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

我希望它像这样工作:

之前:

  • 源文件夹
    • 子文件夹_1
      • 酒吧
    • 子文件夹_2

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

之后:

  • 目标文件夹
    • folder_that_was_already_there
      • 文件2.jpeg
    • some_file.txt
    • 子文件夹_1
      • 酒吧
    • 子文件夹_2

最佳答案

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

关于Python:递归复制文件夹内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23329048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com