標籤:檔案對比 difflib
使用difflib模組對比檔案內容
1 樣本:字串差異對比
vim duibi.py
#!/usr/bin/env python# -*- coding: utf-8 -*-import reimport osimport difflibtex1="""tex1:this is a test for difflib ,just try to get difference of the log現在試試功能是否可行 好呀goodtest那麼試試吧好人"""tex1_lines=tex1.splitlines()tex2="""tex2:this is a test for difflib ,just try to get difference of the log現在試試功能是否可行goodtast那麼試試吧"""tex2_lines=tex2.splitlines()#---------原始對比方法----------#d=difflib.Differ()#diff=d.compare(tex1_lines,tex2_lines)#print '\n'.join(list(diff))#--------html對比方法----------#並修改diff.html的編碼,將ISO-8859-1改為UTF-8格式解析檔案,用於對比中文d=difflib.HtmlDiff()q=d.make_file(tex1_lines,tex2_lines)old_str='charset=ISO-8859-1'new_str='charset=UTF-8'with open('diff.html','w') as f_new:f_new.write(q.replace(old_str,new_str))##############################d=difflib.HtmlDiff()#q=d.make_file(tex1_lines,tex2_lines)#old_str='charset=ISO-8859-1'#new_str='charset=UTF-8'#data=q.replace(old_str,new_str)#fo=open('diff.html','w')#fo.write(data)#fo.close()############################
運行 python duibi.py 生產diff.html
瀏覽器開啟diff.html 查看對比結果。
2 樣本 檔案對比 檔案差異對比代碼 可直接使用 無需修改(包括中文)
用下面指令碼對比 testfile1 testfile2 的差異
vim diff.py
#!/usr/bin/env python# -*- coding: utf-8 -*-import osimport sysimport difflibtry:tfile1=sys.argv[1]tfile2=sys.argv[2]except Exception,e:print "錯誤:"+str(e)print "請準確輸入參數,例如:python diff.py file1 file2"sys.exit()def readfile(filename):try:fileHandle=open(filename,'rb')lines=fileHandle.read().splitlines()fileHandle.close()return linesexcept IOError as error:print('讀取檔案錯誤:'+str(error))sys.exit()if tfile1=="" or tfile2=="":print "請準確輸入參數,例如:python diff.py file1 file2"sys.exit()tfile1_lines=readfile(tfile1)tfile2_lines=readfile(tfile2)#d=difflib.HtmlDiff()#print s.make_file(tfile1_lines,tfile2_lines)#為了產生html能識別中文,可用下面代碼 #修改diff.html的編碼,將ISO-8859-1改為UTF-8#====================================#方法1:#d=difflib.HtmlDiff()#q=d.make_file(tfile1_lines,tfile2_lines)#old_str='charset=ISO-8859-1'#new_str='charset=UTF-8'#data=q.replace(old_str,new_str)#fo=open('diff.html','w')#fo.write(data)#fo.close()#====================================#方法2:#d=difflib.HtmlDiff()#q=d.make_file(tfile1_lines,tfile2_lines)#old_str='charset=ISO-8859-1'#new_str='charset=UTF-8'#fo=open('diff.html','w')#fo.write(q)#fo.close()#with open('diff.html','r') as f:# lines=f.readlines()#with open('diff.html','w') as f_new:# for line in lines:# f_new.write(line.replace(old_str,new_str))#=====================================#方法3:old_str='charset=ISO-8859-1'new_str='charset=UTF-8'd=difflib.HtmlDiff()q=d.make_file(tfile1_lines,tfile2_lines)with open('diff.html','w') as f_new:f_new.write(q.replace(old_str,new_str))
執行python diff.py testfile1 testfile2
產生diff.html
瀏覽器查看檔案對比結果
python使用difflib對比檔案樣本