Python之文件不同對比


有時候會需求對2個文件進行對比,這個用python也可實現

#!/usr/local/bin/python3.5
#-*- coding:utf-8 -*-
import difflib
import sys

try:
    textfile1 = sys.argv[1]
    textfile2 = sys.argv[2]
except Exception as e:
    print("Error:" + str(e))
    print("Usage: 3.py filename1 filename2")
    sys.exit()
    
def readfile(filename):
    try:
        fileHandle = open(filename,'r+')
        text = fileHandle.read().splitlines()
        fileHandle.close()
        return text
    except IOError as error:
        print('Read file Error:' + str(error))
        sys.exit()
        
text1_lines = readfile(textfile1)
text2_lines = readfile(textfile2)

d = difflib.HtmlDiff()
print(d.make_file(text1_lines,text2_lines))

執行生成HTML頁面

./diff123.py nginx1.conf nginx2.conf > diff541854.html

 

效果截圖

 

END!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM