Change language

How do I compare 2 different files line by line in Python?


The Python Standard Library has a module specifically for finding differences between strings / files. To compare two files, you need to get a diff using the difflib library, you can simply call the united_diff function on it. For example, let’s say you have 2 files, file1 and file2, with the following content:

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


Now, to take their difference, use the following code &

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


This will give output &

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