Python Practice › File Handling Programs › Program 19
Compare two files
Write a Python program to compare two files and show the lines that differ.
Output
Same: False --- a.txt +++ b.txt @@ -2 +2 @@ -line two +line 2
Approach
filecmp.cmpfor equal/not equal;difflibto show differences.
Solution
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.