【python】使用difflib对比json差异

之前自己使用python写了方法进行对比json数据,这次使用difflib模块实现:

一个json数据存在text1.txt:

另一个json数据存在text2.txt:

 1、导入difflib模块

import difflib

2、调用difflib中的HtmlDiff类,使用make_file方法对比两个文件内的数据

    m = difflib.HtmlDiff()

    result = m.make_file(read_file('/Users/xmly/Desktop/tools/05_jiami/test/logs/text1'),
                         read_file('/Users/xmly/Desktop/tools/05_jiami/test/logs/text2'))
    #判断是否有变化,有变化则生产报告,没有则不生成报告
    if result.count('<span class="diff_sub">') > 0 or result.count('<span class="diff_chg">') > 0 or result.count(
            '<span class="diff_add">') > 0:

        print("find diff")

        with open('/Users/xmly/Desktop/tools/05_jiami/test/logs/result1.html', 'w', encoding='utf-8') as f:

            f.writelines(result)

    else:

        print("not find diff, no html report generate!")

 输出报告:

猜你喜欢

转载自blog.csdn.net/weixin_43569834/article/details/131861644