You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:将双文件对比代码扩展为主文件与同目录多文件差异对比

Alright, let's adapt your existing text comparison code to work with a master file (file1) and multiple other files in the same folder. Here's a practical, easy-to-modify solution that'll give you clear, readable differences for each pair:

Solution Code
import difflib
import os

def compare_master_with_files(master_filename="file1"):
    # Read the master file content first (only once for efficiency)
    try:
        with open(master_filename, 'r', encoding='utf-8') as master_file:
            master_lines = master_file.readlines()
    except FileNotFoundError:
        print(f"Error: Master file '{master_filename}' not found in the current directory.")
        return
    except Exception as e:
        print(f"Error reading master file: {str(e)}")
        return

    # Get all files in the current directory, excluding the master file
    current_dir = os.getcwd()
    all_files = [
        f for f in os.listdir(current_dir) 
        if os.path.isfile(os.path.join(current_dir, f)) and f != master_filename
    ]

    # Optional: Filter to only include text files (uncomment if needed)
    # all_files = [f for f in all_files if f.endswith('.txt')]

    if not all_files:
        print("No other files found in the current directory to compare.")
        return

    # Compare each target file with the master
    for target_file in all_files:
        print(f"\n{'='*50}")
        print(f"Comparing {master_filename} vs {target_file}")
        print(f"{'='*50}")

        try:
            with open(target_file, 'r', encoding='utf-8') as tf:
                target_lines = tf.readlines()
        except Exception as e:
            print(f"⚠️  Could not read {target_file}: {str(e)}")
            continue

        # Generate unified diff (familiar git-like format)
        diff = difflib.unified_diff(
            master_lines,
            target_lines,
            fromfile=master_filename,
            tofile=target_file,
            lineterm=''
        )

        diff_output = list(diff)
        if not diff_output:
            print("✅  No differences found between the files.")
        else:
            print("\nDifferences:")
            for line in diff_output:
                print(line)

if __name__ == "__main__":
    compare_master_with_files()
Key Features & Explanations
  • Efficient Master File Handling: Reads file1 once upfront instead of reloading it for every comparison, saving time with multiple target files.
  • Automatic File Discovery: Scans the current directory and picks up all files except the master—no need to list them manually. Uncomment the optional filter if you only want to compare .txt files.
  • Readable Diff Format: Uses difflib.unified_diff() to produce a git-style output, making it easy to spot deletions (-), additions (+), and surrounding context lines.
  • Robust Error Handling: Catches missing files, read permissions issues, and other errors, so the script keeps running even if one file fails to load.
  • Clear Visual Separation: Each file comparison is wrapped in a header (=====) so you can quickly distinguish results between different target files.
How to Use
  1. Save this script in the same directory as file1 and your other files (file2, file3, etc.).
  2. Run the script with python your_script_name.py.
  3. If your master file has a different name, just pass it to the function: compare_master_with_files(master_filename="your_custom_master.txt").

内容的提问来源于stack exchange,提问作者Rahul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:31:52