3

我正在尝试使用 difflib 比较两个文件。比较后,如果没有检测到差异,我想打印“No Changes”。如果它们在某些方面有所不同。我想打印那些行。

我试过这样:

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))

如果检测到“没有更改”,它将打印文件的内容。但如果没有区别,我想打印“No Changes”。

4

1 回答 1

3

检查每个元素中的第一个字符是否在开头有或(标记已更改的行)+-

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')
于 2015-10-10T06:28:41.647 回答