Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare two files and print mismatched line number in python?

I have two files which contains same number of lines.

"file1.txt" contains following lines:

 Attitude is a little thing that makes a big difference
 The only disability in life is a bad attitude
 Abundance is, in large part, an attitude
 Smile when it hurts most

"file2.txt" contains:

 Attitude is a little thing that makes a big difference
 Everyone has his burden. What counts is how you carry it
 Abundance is, in large part, an attitude
 A positive attitude may not solve all your problems  

I want to compare two files line by line and if any of the line mismatches between two files i want to

 print "mismatch in line no: 2"
 print "mismatch in line no: 4"   #in this case lineno: 2 and lineno: 4 varies from second file

I tried.but i can print only the line in file1 which is differ from line in file2.can't able to print the line number of mismatched lines.??

 My code:
 with open("file1.txt") as f1:
    lineset = set(f1)
 with open("file2.txt") as f2:
    lineset.difference_update(f2)
    for line in lineset:
        print line
like image 413
user3116273 Avatar asked Dec 20 '22 20:12

user3116273


1 Answers

Using itertools.izip and enumerate:

import itertools

with open('file1.txt') as f1, open('file2.txt') as f2:
    for lineno, (line1, line2) in enumerate(itertools.izip(f1, f2), 1):
        if line1 != line2:
            print 'mismatch in line no:', lineno
like image 82
falsetru Avatar answered May 03 '23 22:05

falsetru