Python模块之Difflib2017年7月8日参考书籍:《Python自动化运维——技术与最佳实践》作者:李天斯1.什么是difflibDifflib作为python的标准库,无需安装,作用是对比文本之间的差异,而且支持输出可读性比较强的HTML文档,与Linux下的vimdiff命令类似,我们可以比对文本、配置文件之间的差异,在版本控制方面非常有用。2.difflib的简单使用2.1Differ的简单使用2.1.1编写python代码root@kali:/mnt/disk/python/difflib#catdifflib_0.py#!/usr/bin/envpythonimportdifflibtext1='''IloveHaiYanIveryloveHaiYanShe'stheoneIlovethemost.'''text2='''IloveLiWangIveryloveLiWangI'mhisfavoriteperson.'''d=difflib.Differ()print(list(d.compare(text1,text2)))2.1.2执行脚本输出#pythondifflib_0.py['\n','I','','l','o','v','e','','+L','-H','-a','i','-Y','+W','a','n','+g','\n','I','','v','e','r','y','','l','o','v','e','','+L','-H','-a','i','-Y','+W','a','n','+g','\n','-S','+I',+','+m','+','h','+i','-e',-','s','','+f','+a','+v','+o','+r','+i','t','-h','e','','+p','+e','+r','+s','o','n','-e','-','-I','-','-l','-o','-v','-e','-','-t','-h','-e','-','-m','-o','-s','-t','.','\n']输出了看不懂的列表,打印列表后再进行查看增加代码:list1=list(d.compare(text1,text2))forlineinlist1:ifline==\n:print(\n)print(%s%(line),end='')执行代码:#python3difflib_0.pyIlove+L-H-ai-Y+Wan+gIverylove+L-H-ai-Y+Wan+g-S+I+'+m+h+i-e-'s+f+a+v+o+r+it-he+p+e+r+son-e--I--l-o-v-e--t-h-e--m-o-s-t.符号含义:+:包含在第一个序列中,但不包含第二个序列-:包含在第二个序列中,但是不包含第一个序列2.2HtmlDiff的简单使用2.2.1向文件写入内容#echo-eIloveHaiYan\nIveryloveHaiYan\nShe'stheoneIlovethemost.test_1#echo-eIloveLiWang\nIveryloveLiWang\nI'mhisfavoritepersontest_22.2.2编写python代码#catdifflib_1.py#!/usr/bin/envpythonimportdifflibdefopen_files(filename):files=open(filename,'rb')text=files.read().splitlines()files.close()returntextd=difflib.HtmlDiff()text_1=open_files('test_1')text_2=open_files('test_2')print(d.make_file(text_1,text_2))2.2.3执行脚本,用网页打开#pythondifflib_1.py/mnt/disk/html/index.html3.difflib案例3.1需求需求:利用python实现一个功能,只需要执行[python脚本名称文件1文件2],只需要打开浏览器输入网址就能够看见文件比对效果3.2流程图流程图:3.3代码编写:catdifflib_2.py#!/usr/bin/envpython#exitargvimportsys#pathimportos#HtmlDiffimportdifflibhtml_files='/mnt/disk/html/index.html'#Determinewhethertheparameterexiststry:script_name=sys.argv[0]file1=sys.argv[1]file2=sys.argv[2]except:print(%sUsing:%sfilename1filename2%(script_name,script_name))sys.exit()#Function1defdealwith_files(filename):#openfilestry:files=open(filename,'rb')#readfilestext=files.read().splitlines()#closefilesfiles.close()except:print(Openfilesfail)sys.exit()#returnfilesreturntext#Determineifthefilesexistsifos.path.isfile(file1)andos.path.isfile(file2):d=difflib.HtmlDiff()try:print_files=open(html_files,'w')print_files.write(d.make_file(dealwith_files(file1),dealwith_files(file2)))print_files.close()except:print(write%sfail%(html_files))#print(d.make_file(dealwith_files(file1),dealwith_files(file2)))else:print(%sor%sisnotsuchfile%(file1,file2))sys.exit()3.4执行脚本输出#chmod755difflib_2.py#./difflib_2.pydebconf.confdebconf.conf.bak#chmod是赋予脚本执行权限,执行difflib_2py参数为debconf.confdebconf.conf.bak,没有任何输出,则证明执行OK3.5效果刷新网页