Python 2 个文件的 difflib,行号不正确

Python difflib for 2 files, with incorrect line numbers

我必须比较 Python 中的 2 个文件,我正在使用 difflib. I tried this separately with ndiff and then with unified_diff. The contents of the 2 files are straightforward, per the example here:

File_1.txt:

User1 US
User2 US
User3 US

File_2.txt:

User1 US
User2 US
User3 NG

这是对我有用的代码(没有正确的行号):

import difflib
import sys

def dif_wr(d):
    for i,line in enumerate(d):
        sys.stdout.write('{} {}' .format(i+1,line))

# Method 1
with open('File_1.txt', 'r') as h0:
    with open('File_2.txt', 'r') as h1:
        dif = difflib.unified_diff(h0.readlines(),\
                                   h1.readlines(),\
                                   fromfile='File_1.txt',tofile='File_2.txt')
dif_wr(dif)

# Method 2
with open('File_1.txt','r') as fl1, open('File_2.txt','r') as fl2:
    dif2 = difflib.ndiff(fl1.readlines(),fl2.readlines())
dif_wr(dif2)

输出是:

1 --- File_1.txt
2 +++ File_2.txt
3 @@ -1,3 +1,3 @@
4  User1 US
5  User2 US
6 -User3 US7 +User3 NG1   User1 US
2   User2 US
3 - User3 US4 ?       ^^
5 + User3 NG6 ?       ^^

行号似乎不正确。似乎他们从第 4 行开始,这是错误的行。

问题

有没有办法通过输出获得正确的行号?

unified_diff 的文档说它需要一个参数 n:

Unified diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in an inline style (instead of separate before/after blocks). The number of context lines is set by n which defaults to three. The number of context lines is set by n which defaults to three.

另外,参数lineterm:

For inputs that do not have trailing newlines, set the lineterm argument to "" so that the output will be uniformly newline free.

要获得所需的输出,您需要取下行终止符,然后在输出中重新添加它们。您还需要将上下文行设置为零:

import difflib
import sys    

def dif_wr(d):
    for i, line in enumerate(d):
        sys.stdout.write('{} {}\n'.format(i + 1, line))

一些使用字符串而不是文件的示例代码:

from StringIO import StringIO

file1 = """User1 US
User2 US
User3 US"""

file2 = """User1 US
User2 US
User3 NG"""

dif2 = difflib.unified_diff(StringIO(file1).readlines(),
                            StringIO(file2).readlines(),
                            fromfile='File_1.txt',
                            tofile='File_2.txt',
                            n=0,
                            lineterm="")
dif_wr(dif2)

输出:

1 --- File_1.txt
2 +++ File_2.txt
3 @@ -3,1 +3,1 @@
4 -User3 US
5 +User3 NG