python比較兩個檔案的差異

來源:互聯網
上載者:User

標籤:python比較兩個檔案的差異


使用python指令碼比較兩個檔案的差異內容並輸出到html文檔中,可以通過瀏覽器開啟查看。

一、指令碼使用

  1. 對比nginx設定檔的差異

 python python_diff_file.py -f1 web26.conf -f2 web103.conf

二、指令碼內容

#!/usr/bin/python# -*- coding: utf-8 -*-"""1.difflib的HtmlDiff類建立html表格用來展示檔案差異,通過make_file方法2.make_file方法使用make_file(fromlines, tolines [, fromdesc][, todesc][, context][, numlines])用來產生一個包含表格的html檔案,其內容是用來展示差異。fromlines和tolines,用於比較的內容,格式為字串組成的列表fromdesc和todesc,選擇性參數,對應的fromlines,tolines的差異化檔案的標題,預設為空白字串context 和 numlines,選擇性參數,context 為True時,只顯示差異的上下文,為false,顯示全文,numlines預設為5,當context為True時,控制展示內容相關的行數,當context為false時,控制不同差異的高亮之間移動時“next”的開始位置3.使用argparse傳入兩個需要對比的檔案"""import difflibimport argparseimport sys# 建立開啟檔案函數,並按分行符號分割內容def readfile(filename):    try:        with open(filename, ‘r‘) as fileHandle:            text = fileHandle.read().splitlines()        return text    except IOError as e:        print("Read file Error:", e)        sys.exit()# 比較兩個檔案並輸出到html檔案中def diff_file(filename1, filename2):    text1_lines = readfile(filename1)    text2_lines = readfile(filename2)    d = difflib.HtmlDiff()    # context=True時只顯示差異的上下文,預設顯示5行,由numlines參數控制,context=False顯示全文,差異部分顏色高亮,預設為顯示全文    result = d.make_file(text1_lines, text2_lines, filename1, filename2, context=True)    # 內容儲存到result.html檔案中    with open(‘result.html‘, ‘w‘) as resultfile:        resultfile.write(result)    # print(result)if __name__ == ‘__main__‘:    # 定義必須傳入兩個參數,使用格式-f1 filename1 -f2 filename    parser = argparse.ArgumentParser(description="傳入兩個檔案參數")    parser.add_argument(‘-f1‘, action=‘store‘, dest=‘filename1‘, required=True)    parser.add_argument(‘-f2‘, action=‘store‘, dest=‘filename2‘, required=True)    given_args = parser.parse_args()    filename1 = given_args.filename1    filename2 = given_args.filename2    diff_file(filename1, filename2)

三、對比結果

650) this.width=650;" src="http://s4.51cto.com/wyfs02/M01/8B/48/wKioL1hJAeiyb5LHAABgA5Dyjrg370.png-wh_500x0-wm_3-wmp_4-s_491280325.png" style="float:none;" title="01.png" alt="wKioL1hJAeiyb5LHAABgA5Dyjrg370.png-wh_50" />

650) this.width=650;" src="http://s4.51cto.com/wyfs02/M02/8B/4B/wKiom1hJAenhteM_AACBZJG7sIM148.png-wh_500x0-wm_3-wmp_4-s_1440472057.png" style="float:none;" title="02.png" alt="wKiom1hJAenhteM_AACBZJG7sIM148.png-wh_50" />


本文出自 “linux之路” 部落格,請務必保留此出處http://hnr520.blog.51cto.com/4484939/1880736

python比較兩個檔案的差異

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.