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
file1once 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
.txtfiles. - 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
- Save this script in the same directory as
file1and your other files (file2, file3, etc.). - Run the script with
python your_script_name.py. - 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
相关产品推荐
相关产品推荐

