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
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
2 Comments
Bryan Oakley
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.
user1229351
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.
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
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
user1229351
it should be python script.not prebuilt tool