alex_bn_lee

导航

[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 2025-01-14 07:01  McDelfino  阅读(47)  评论(0)    收藏  举报