使用Python自帶difflib模塊進行文件內容差異對比


difflib_text.py

#!/usr/bin/python
import difflib
import sys

try:
    textfile1=sys.argv[1]
    textfile2=sys.argv[2]
except Exception,e:
    print "Error:"+str(e)
    print "Usage: difflib_text.py filename1 filename2"
    sys.exit()

def readfile(filename):
    try:
	fileHandle = open (filename,'rb')
        text = fileHandle.read().splitlines()
   	fileHandle.close()
        return text
    except IOError as error:
    	print('Read file Error:'+str(error))
	sys.exit()

if textfile1=="" or textfile2=="":
    print "Usage: simple3.py filename1 filename2"
    sys.exit()

text1_lines = readfile(textfile1)
text2_lines = readfile(textfile2)

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

測試:python difflib_text.py nginxdiff.conf nginxdiff2.conf

結果:

 

搜索


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com