以前に Python を使用して JSON データを比較するメソッドを作成しましたが、今回は difflib モジュールを使用して次のことを実現しました。
json データは text1.txt に存在します。
別の json データが text2.txt に存在します。
1. difflib モジュールをインポートする
import difflib
2. difflib の HtmlDiff クラスを呼び出し、make_file メソッドを使用して 2 つのファイルのデータを比較します。
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!")
出力レポート: