Python使用difflib模塊比較兩個文件內容異同,同時輸出html易瀏覽

因工作需求,需要對比連個文件異同,並輸出html格式來對比。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import difflib

def read_file(filename):
    try:
        with open(filename, 'r') as f:
            return f.readlines()
    except IOError:
        print("ERROR: 沒有找到文件:%s或讀取文件失敗!" % filename)
        sys.exit(1)

def compare_file(file1, file2, out_file):
    file1_content = read_file(file1)
    file2_content = read_file(file2)
    d = difflib.HtmlDiff()
    result = d.make_file(file1_content, file2_content)
    old_str='charset=ISO-8859-1'
    new_str='charset=UTF-8'
    with open(out_file, 'w') as f:
        f.writelines(result.replace(old_str,new_str))

if __name__ == '__main__':
    compare_file(r'd:\1\a.log', r'd:\2\a.log', r'd:\result.html')

輸出爲一個result.html文件,打開後已於瀏覽。

參考:Python--比較文件內容
python使用difflib對比文件示例
Python自動化運維筆記(四):使用difflib模塊實現文件內容差異對比

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章