difflib模块文件内容差异对比
简介
difflib作为python的标准库模块,无需安装,作用是比对文本之间的差异,且支持输出可读性比较强的HTML文档,与Linux下的diff命令相似。可以使用该模块比对代码和配置文件的差异,在版本控制方面非常有用。Python2.3以后的版本默认自带difflib模块,无需额外安装。
使用方法
- 字符串差异的比对
#!/usr/bin/env python # -*- coding: utf-8 -*- import difflib text1 = """text1: This module provides classes and functions for comparing sequences. including HTML and context and unified diffs. difflib document v7.4 add string """ text1_lines = text1.splitlines() text2 = """text2: This module provides classes and functions for Comparing sequences. including HTML and context and unified diffs. difflib document v7.5""" text2_lines = text2.splitlines() d = difflib.Differ() #创建Differ对象 diff = d.compare(text1_lines,text2_lines) #采用compare方法对字符串进行比较 print "\n".join(list(diff)) #join将序列中的元素以指定的字符连接生成一个新的字符串str.join(sequence) 结果显示 - text1: ? ^ + text2: ? ^ - This module provides classes and functions for comparing sequences. ? ^ + This module provides classes and functions for Comparing sequences. ? ^ including HTML and context and unified diffs. - difflib document v7.4 ? ^ + difflib document v7.5 ? ^ - add string
各个差异符号表示含义
'-':包含在第一个序列行中,不包含在第二个序列行中
'+':包含在第二个序列行中,不包含在第一个序列行中
'':两个序列行一致
'?':标志两个序列行存在增量差异
'^':标志出两个序列存在的差异字符
- 生成美观的HTML文档
采用HtmlDiff()的make_file()方法就可以生成美观的HTML文档,可以对上面的例子进行如下修改:
d = difflib.Differ() diff = d.compare(text1_lines,text2_lines) print "\n".join(list(diff))
将以上修改为
d = difflib.HtmlDiff() diff = d.make_file(text1_lines,text2_lines) print diff
将以上程序保存为sample2.py ,运行python sample2.py > diff.html,用浏览器打开保存的html文件
- 比对nginx配置文件差异
当我们维护多个Nginx配置时,时长会比对不同版本配置文件的差异,使运维人员更加清晰地了解不同版本迭代后的更新项,实现的思路是读取两个需对比的配置文件,再以换行符作为分隔符,调用difflib.HtmlDiff()生成HTML格式的差异文档。具体实现如下:
#!/usr/bin/env python # -*- coding: utf-8 -*- import difflib import sys try: textfile1 = sys.argv[1] textfile2 = sys.argv[2] except Exception,e: print "Error:" +str(e) print "Usage: python sample3.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() text1_lines = readfile(textfile1) text2_lines = readfile(textfile2) d = difflib.HtmlDiff() print d.make_file(text1_lines,text2_lines)
运行代码 ython sample3.py nginx.conf.v1 nginx.conf.v2 > sample3_diff.html
通过浏览器查看两个文件差异
附nginx配置文件