alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[1090] Use Python to compare the files in two folders and merge their contents

You can use Python to compare the files in two folders and merge their contents. Here’s a simple approach using the filecmp and shutil modules to recognize differences and merge files:

Step-by-Step Guide

  1. Compare Files in Two Folders: Use the filecmp module to identify files that are different or missing.
  2. Merge Files: Use the shutil module to copy files from one folder to another.

Example Code

import os
import filecmp
import shutil
def compare_and_merge_folders(folder1, folder2, merged_folder):
# Ensure the merged_folder exists
if not os.path.exists(merged_folder):
os.makedirs(merged_folder)
# List of files in both folders
files1 = set(os.listdir(folder1))
files2 = set(os.listdir(folder2))
# Files unique to each folder
unique_to_folder1 = files1 - files2
unique_to_folder2 = files2 - files1
# Common files
common_files = files1.intersection(files2)
# Copy unique files from folder1 to merged_folder
for file in unique_to_folder1:
shutil.copy(os.path.join(folder1, file), os.path.join(merged_folder, file))
# Copy unique files from folder2 to merged_folder
for file in unique_to_folder2:
shutil.copy(os.path.join(folder2, file), os.path.join(merged_folder, file))
# Merge common files
for file in common_files:
if not filecmp.cmp(os.path.join(folder1, file), os.path.join(folder2, file), shallow=False):
# If files are different, you can handle the merging logic here
# For simplicity, let's copy the version from folder1
shutil.copy(os.path.join(folder1, file), os.path.join(merged_folder, file))
else:
# If files are the same, copy any version
shutil.copy(os.path.join(folder1, file), os.path.join(merged_folder, file))
# Example usage
folder1 = 'path/to/folder1'
folder2 = 'path/to/folder2'
merged_folder = 'path/to/merged_folder'
compare_and_merge_folders(folder1, folder2, merged_folder)

Explanation

  • File Comparison: The filecmp.cmp function checks if files are identical.
  • Unique Files: Files unique to each folder are copied directly to the merged folder.
  • Common Files: For common files, you can add logic to merge their contents. In this example, it simply copies the version from folder1 if they differ.

Feel free to modify the merging logic as needed. Happy coding! 🐍💻

Let me know if you need further details or have specific requirements for the merge process!

posted on   McDelfino  阅读(7)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2023-01-14 【800】机器学习特征重要性可视化
2023-01-14 【799】lightGBM实现
2023-01-14 【798】Python中通过seaborn绘制violin plot
2021-01-14 【521】通过压缩文件安装 python library
点击右上角即可分享
微信分享提示