1. 程式人生 > >Python使用difflib模組比較兩個檔案內容異同,同時輸出html易瀏覽

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模組實現檔案內容差異對比