The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Build a “what changed_” file comparison tool

Here’s a complete implementation of a simple “What Changed?” file comparison tool in Python. This tool takes two files as input, compares their contents line by line, and outputs a clear difference report. It supports added, removed, and modified lines.

python
import difflib import sys import argparse def read_file(filepath): with open(filepath, 'r', encoding='utf-8') as file: return file.readlines() def compare_files(file1_lines, file2_lines, file1_name="File1", file2_name="File2"): diff = difflib.unified_diff( file1_lines, file2_lines, fromfile=file1_name, tofile=file2_name, lineterm='' ) return list(diff) def highlight_changes(diff_lines): for line in diff_lines: if line.startswith('+') and not line.startswith('+++'): print(f"33[92m{line}33[0m") # Green for additions elif line.startswith('-') and not line.startswith('---'): print(f"33[91m{line}33[0m") # Red for deletions else: print(line) def main(file1_path, file2_path): file1_lines = read_file(file1_path) file2_lines = read_file(file2_path) diff = compare_files(file1_lines, file2_lines, file1_path, file2_path) if not diff: print("No changes detected.") else: print("Changes found:n") highlight_changes(diff) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Compare two text files and highlight differences.") parser.add_argument("file1", help="Path to the original file") parser.add_argument("file2", help="Path to the updated file") args = parser.parse_args() main(args.file1, args.file2)

Features

  • Uses difflib.unified_diff to show changes in Unix diff style.

  • Highlights additions in green and deletions in red in the terminal using ANSI escape codes.

  • Displays file names and change context.

Usage

  1. Save this script as what_changed.py.

  2. Run it from the command line:

bash
python what_changed.py old_version.txt new_version.txt

Optional Enhancements

  • Add support for side-by-side comparison.

  • Include GUI support using Tkinter or a web interface.

  • Add word-level difference detection using difflib.ndiff().

Let me know if you want a version that runs in the browser or as a web app.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About