Computer >> Computer tutorials >  >> Programming >> Python

How to compare two different files line by line in Python?


The Python standard library has a module specifically for the purpose of finding diffs between strings/files. To get a diff using the difflib library, you can simply call the united_diff function on it. For example, Lets say you have 2 files, file1 and file2 with the following content −

file1:
Hello
People
of
the
world
file2:
Hello
People
from
India

Example

Now to take their diff use the following code −

import difflib
with open('file1') as f1:
    f1_text = f1.read()
with open('file2') as f2:
    f2_text = f2.read()
# Find and print the diff:
for line in difflib.unified_diff(f1_text, f2_text, fromfile='file1', tofile='file2', lineterm=''):
    print line

Output

This will give the output −

--- file1
+++ file2
@@ -1,5 +1,4 @@
 Hello
 People
-of
-the
-world
+from
+India