Compare two files

from difflib import ndiff f1 = open('file1.txt').read().splitlines(True) f2 = open('file2.txt').read().splitlines(True) diff = ndiff(f1 , f2) print(''.join(diff)) 

In the result I get all the lines - the same and different. How can I display only different / missing / new lines in the result? Those. Do not display the same data in both files.

  • aside: use named parameters for boolean parameters: .splitlines(keepends=True) more readable than .splitlines(True) - jfs

1 answer 1

If the result is completely satisfactory, except for the presence of lines common to the two files, it is enough to filter the lines starting with two spaces:

 print(''.join([line for line in diff if not line.startswith(' ')])) 

See Differ format .