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

标签 python python-2.7 file-comparison

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

"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  

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

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

我试过了。但是我只能打印 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

最佳答案

使用 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

关于python - 如何比较两个文件并在 python 中打印不匹配的行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20686674/

相关文章:

perl - 使用 perl md5 比较两个文件

linux - 基于另一个 file_2 从 file_1 获取行

python - pyFMI Modelica : The FMU contains no binary for this platform

python - 有向图 - SQLAlchemy ORM

python - django - 根据翻译后的名称在管理界面中对模型进行排序

python - 为什么 file_object.tell() 会为不同位置的文件提供相同的字节?

Python:装饰器可以从 foo1() 访问参数并将其提供给 foo2() 吗?

python - 如何更改数据框 Python 中的值

python-2.7 - pyclipper 中无法缩放 - TypeError : 'Zero' object is not iterable

ruby - 我如何在 Ruby 1.9 中比较两个文件?