我正在尝试使用difflib比较两个文件。 比较后,如果没有检测到差异,我想打印“无变化”。 如果在某些方面存在差异。我想打印那些线。
我试过这样:
with open("compare.txt") as f, open("test.txt") as g:
flines = f.readlines()
glines = g.readlines()
d = difflib.Differ()
diff = d.compare(flines, glines)
print("\n".join(diff))
如果检测到“无变化”,它将打印文件的内容。但如果没有差异,我想打印“无变化”。
答案 0 :(得分:2)
检查每个元素中的第一个字符是否在开头有+
或-
(标记该行已更改):
with open("compare.txt") as f, open("test.txt") as g:
flines = f.readlines()
glines = g.readlines()
d = difflib.Differ()
diffs = [x for x in d.compare(flines, glines) if x[0] in ('+', '-')]
if diffs:
# all rows with changes
else:
print('No changes')