Check diff between two files in Python

Check diff between two files in Python

In Today I Learned(TIL) series, I'm going to explore python standard module called difflib.

What is difflib

difflib is a built-in standard python library used to find deltas between files and objects.

How to use it

  • Load file1 and file2 content
  • choose a difflib algorithm from unified_diff context_diff ndiff
  • print the diff

import difflib
 with open(file1) as f1:
            f1_content = f1.readlines()
 with open(file2) as f2:
            f2_content = f2.readlines()

diff = difflib.unified_diff(
                f1_content,
                f2_content,
                file1,
                file2,
                n=lines,
            )

diff = difflib.context_diff(
                f1_content,
                f2_content,
                file1,
                file2,
                n=lines,
            )
diff = difflib.ndiff(f1_content, f2_content)

Demo project

Used difflib and rich to develop a rich diff viewer. Code is opensource --> github.com/sureshdsk/rich-diff