我必须在 Python 中比较 2 个文件,并且我正在使用 difflib 。我分别尝试了 ndiff然后用 unified_diff 。根据示例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
关于2 个文件的 Python difflib,行号不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213344/