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

我有2个文件称为“主机”(在不同目录中)

我想使用python比较它们,以查看它们是否相同。如果它们不相同,我想在屏幕上打印差异。

到目前为止,我已经尝试过

hosts0 = open(dst1 + "/hosts","r") 
hosts1 = open(dst2 + "/hosts","r")

lines1 = hosts0.readlines()

for i,lines2 in enumerate(hosts1):
    if lines2 != lines1[i]:
        print "line ", i, " in hosts1 is different \n"
        print lines2
    else:
        print "same"

但是当我运行它时,我得到

File "./audit.py", line 34, in <module>
  if lines2 != lines1[i]:
IndexError: list index out of range

这意味着其中一台主机比另一台主机具有更多的线路。
有没有更好的方法比较两个文件并报告差异?

参考方案

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

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

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…

无法注释掉涉及多行字符串的代码 - python

基本上,我很好奇这为什么会引发语法错误,以及如何用Python的方式来“注释掉”我未使用的代码部分,例如在调试会话期间。''' def foo(): '''does nothing''' ''' 参考方案 您可以使用三重双引号注释掉三重单引…