Compare two files

EasyFile Handling Programs · 19 of 38

Write a Python program to compare two files and show the lines that differ.

Advertisement
Output
Same: False
--- a.txt
+++ b.txt
@@ -2 +2 @@
-line two
+line 2

Approach

  1. filecmp.cmp for equal/not equal; difflib to show differences.

Solution

Python
import difflibimport filecmp with open("a.txt", "w") as f:    f.write("line one\nline two\nline three\n")with open("b.txt", "w") as f:    f.write("line one\nline 2\nline three\n") print("Same:", filecmp.cmp("a.txt", "b.txt", shallow=False))with open("a.txt") as a, open("b.txt") as b:    for line in difflib.unified_diff(a.readlines(), b.readlines(), "a.txt", "b.txt", n=0):        print(line.rstrip("\n"))
Output
Same: False
--- a.txt
+++ b.txt
@@ -2 +2 @@
-line two
+line 2

Line by line

Line 9

shallow=False compares the contents, not just size and date.

Line 11

A unified diff shows removed lines with - and added lines with +.

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

Leave a Comment