3

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

1
  • 3
    difflib might be of interest Commented Apr 17, 2012 at 19:15

3 Answers 3

2
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

Sign up to request clarification or add additional context in comments.

2 Comments

If you have a single extra line in f1 it will report that every line after that is different. Comparing line by line is only useful if the files are mostly tne same except some intra-line differences.
my problem is what you said, i don't want this to be happen. i need only differences not just if the first line not match all of next line print on screen as not matched line.
1

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

Comments

0

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.

1 Comment

it should be python script.not prebuilt tool

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.