You might be able to use the difflib
module. Here's a simple example using its difflib.Differ
class:
import difflib
import sys
with open('file1.txt') as file1, open('file2.txt') as file2:
line_formatter = '{:3d} {}'.format
file1_lines = [line_formatter(i, line) for i, line in enumerate(file1, 1)]
file2_lines = [line_formatter(i, line) for i, line in enumerate(file2, 1)]
results = difflib.Differ().compare(file1_lines, file2_lines)
sys.stdout.writelines(results)
Output:
1 Attitude is a little thing that makes a big difference
- 2 The only disability in life is a bad attitude
+ 2 Everyone has his burden. What counts is how you carry it
3 Abundance is, in large part, an attitude
- 4 Smile when it hurts most
+ 4 A positive attitude may not solve all your problems
The minus and plus characters in the first column indicate lines that were replaced in typical diff
utility program style. The absence of any indicator means the line was the same in both files -- you could suppress the printing of those if you wished, but to keep the example simple everything the compare()
method creates is being printed.
For reference, here's the contents of the two files side-by-side with line numbers shown:
1 Attitude is a little thing that makes a big difference Attitude is a little thing that makes a big difference
2 The only disability in life is a bad attitude Everyone has his burden. What counts is how you carry it
3 Abundance is, in large part, an attitude Abundance is, in large part, an attitude
4 Smile when it hurts most A positive attitude may not solve all your problems