我想递归地复制文件夹的内容而不复制已经存在的文件。此外,目标文件夹已经存在并且包含文件。 我尝试使用 shutils.copytree(source_folder, destination_folder) , 但它没有做我想做的事。
我希望它像这样工作:
之前:
- 源文件夹
- 子文件夹_1
- 富
- 酒吧
- 子文件夹_2
- 子文件夹_1
- 目标文件夹
- folder_that_was_already_there
- 文件2.jpeg
- some_file.txt
- 子文件夹_1
- 富
- folder_that_was_already_there
之后:
- 目标文件夹
- folder_that_was_already_there
- 文件2.jpeg
- some_file.txt
- 子文件夹_1
- 富
- 酒吧
- 子文件夹_2
- folder_that_was_already_there
最佳答案
我在 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/