Compare two text files in python

I want to compare two test files in python (these are actually Windows registry files (.reg), but they are all text files). im looking for all the differences between the two files, not just the first line, which does not match the second file. thanks in advance

+3
source share
3 answers
f1 = open(filepath1)
f2 = open(filepath2)

lines = f2.readlines()
for i,line in enumerate(f1):
    if line != lines[i]:
        print "line", i, "is different:"
        print '\t', line
        print '\t', lines[i]
        print "\t differences in positions:", ', '.join(map(str, [c for c in range(len(line)) if line[c]!= lines[i][c]]))

Hope this helps

+1
source

Take a look at http://docs.python.org/library/difflib.html

Here is an example of how it works (although there are many other use cases and output formats):

>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
>>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'):
...     sys.stdout.write(line)   
--- before.py
+++ after.py
@@ -1,4 +1,4 @@
-bacon
-eggs
-ham
+python
+eggy
+hamster
 guido
+1
source

, Gnu32Diff. ​​ X Linux, vimdiff (AKA vim -d, ​​vim, vimdiff), .

0

All Articles