user1229351
user1229351

Reputation: 2035

compare two text file in python

I want to compare two test file in python.(actually they are windows registry files(.reg) but they are all text). im looking for all the differences between two files and not just the first line which is not the same of second file. thanks in advance

Upvotes: 3

Views: 2855

Answers (3)

dkamins
dkamins

Reputation: 21918

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

Here's an example of how it works (though 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

Upvotes: 1

Jeff Tratner
Jeff Tratner

Reputation: 17076

If you just need to do it once or twice, you might consider using Gnu32Diff. If you have OS X or Linux installed, you can use vimdiff (AKA vim -d, but if you have vim installed it installs a vimdiff command as well), which is quite simple and easy to use.

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113955

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

Upvotes: 2

Related Questions