使用Python比较两个文本文件时,如何跳过空白行?

时间:2013-11-19 15:04:25

标签: python-2.7 diff

我使用以下代码比较两个文本文件

import difflib

with open("D:/Dataset1/data/1/hy/0/Info.txt") as f, open("D:/Dataset1/data/2/hy/0/Info.txt") as g:
    flines= f.readlines()
    glines= g.readlines()
    d = difflib.Differ()
    diff = d.compare(flines, glines)
print("\n".join(diff))

我得到了这个结果:

- Local Config:   HKEY_CURRENT_USER\Software\Microsoft\Uwxa\Kavi

?                                                      ^^^  ^^^

+ Local Config:   HKEY_CURRENT_USER\Software\Microsoft\Otgad\Hyikqomi

?                                                      ^^^ + ^^^^^^^

任何想法如何跳过空行?

2 个答案:

答案 0 :(得分:0)

difflib.Differ.compare的结果已包含换行符。

>>> import difflib
>>> list(difflib.Differ().compare(['1\n', '2\n'], ['1\n', '3\n']))
['  1\n', '- 2\n', '+ 3\n']
>>> print ''.join(difflib.Differ().compare(['1\n', '2\n'], ['1\n', '3\n']))
  1
- 2
+ 3

将结果与\n结合,添加其他换行符。

替换以下行:

print("\n".join(diff))

with(用空字符串而不是换行符连接):

print("".join(diff))

答案 1 :(得分:0)

我无法使用difflib.ndiff的linejunk函数(我认为这会是更好的解决方案)。但是最后使用对我有用的strip()函数:

diff = difflib.ndiff(file1.readlines(), file2.readlines());

for x in diff:

if x.strip() == "+" or x.strip() == "-":
        print("Blank Line... Ignore")
else:
        print("Non Blank");