您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

比较两个文件在python中报告差异

比较两个文件在python中报告差异

import difflib

lines1 = '''
dog
cat
bird
buffalo
gophers
hound
horse
'''.strip().splitlines()

lines2 = '''
cat
dog
bird
buffalo
gopher
horse
mouse
'''.strip().splitlines()

# Changes:
# swapped positions of cat and dog
# changed gophers to gopher
# removed hound
# added mouse

for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm=''):
    print line

输出以下内容

--- file1
+++ file2
@@ -1,7 +1,7 @@
+cat
 dog
-cat
 bird
 buffalo
-gophers
-hound
+gopher
 horse
+mouse

此差异为您提供了上下文-周围的线条以帮助您清楚文件的不同之处。您可以在此处看到两次“ cat”,因为它已从“ dog”下方删除,并在其上方添加

您可以使用n = 0删除上下文。

for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0):
    print line

输出

--- file1
+++ file2
@@ -0,0 +1 @@
+cat
@@ -2 +2,0 @@
-cat
@@ -5,2 +5 @@
-gophers
-hound
+gopher
@@ -7,0 +7 @@
+mouse

但是现在它充满了“ @@”行,告诉您文件中已更改的位置。让我们删除多余的行以使其更具可读性。

for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0):
    for prefix in ('---', '+++', '@@'):
        if line.startswith(prefix):
            break
    else:
        print line

提供以下输出

+cat
-cat
-gophers
-hound
+gopher
+mouse

现在,您要它做什么?如果您忽略所有已删除的行,则不会看到“猎犬”已被删除。如果您很高兴只显示文件中的添加内容,则可以执行以下操作:

diff = difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0)
lines = list(diff)[2:]
added = [line[1:] for line in lines if line[0] == '+']
removed = [line[1:] for line in lines if line[0] == '-']

print 'additions:'
for line in added:
    print line
print
print 'additions, ignoring position'
for line in added:
    if line not in removed:
        print line

输出

additions:
cat
gopher
mouse

additions, ignoring position:
gopher
mouse

您现在可能已经知道,有两种方法可以“打印”两个文件的差异,因此,如果需要更多帮助,则需要非常具体。

python 2022/1/1 18:45:13 有323人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶