如何在python中比较两个文件并打印不匹配的行号?

use*_*273 4 python file-comparison python-2.7

我有两个包含相同行数的文件.

"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  
Run Code Online (Sandbox Code Playgroud)

我想逐行比较两个文件,如果我想要的两个文件之间的任何行不匹配

 print "mismatch in line no: 2"
 print "mismatch in line no: 4"   #in this case lineno: 2 and lineno: 4 varies from second file
Run Code Online (Sandbox Code Playgroud)

我试过.但是我只能打印file1中与file2中的行不同的行.不能打印不匹配行的行号.

 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
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 6

使用itertools.izipenumerate:

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
Run Code Online (Sandbox Code Playgroud)