[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
- Compare Files in Two Folders: Use the
filecmp
module to identify files that are different or missing. - 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!
分类:
Python Study
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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