文件内容对比
#!/usr/bin/python
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()
diff = d.compare(text1_lines, text2_lines)
print '\n'.join(list(diff))
对比符号含义说明
‘-’ 第一个序列有,第二个无
‘+’ 第一个序列无,第二个有
‘ ’ 两个一致
‘?’ 两序列存在增量差异
'^' 标志出两序列的差异字符
采用HtmlDiff()类的make_file()方法可生成美观的HTML文档
上述示例的以下部分
d = difflib.Differ()
diff = d.compare(text1_lines, text2_lines)
print '\n'.join(list(diff))
替换为
d = difflib.HtmlDiff()
print d.make_file(text1_lines, text2_lines)
文件命名为simple2.py,执行 python simple2.py > diff.html,可生成对比文件
Nginx配置文件对比
#!/usr/bin/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: simple3.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 simple3.py nginx.conf.v1 nginx.conf.v2 > diff.html
文件与目录差异对比
filecmp模块的三个操作方法
cmp 单文件对比
cmpfiles 多文件对比
dircmp 目录对比
filecmp.cmp(f1,f2[,shallow]) 对比文件f1、f2,相同返回True,否则False,
shallow默认为True,只根据os.stat()方法返回的文件基本信息对比,如最后访问时间、修改时间、状态改变时间等
shallow为False时,则os.stat()、文件内容同时进行校验
>>> import filecmp
>>> filecmp.cmp("/root/test/a","/root/test/b")
False
>>> filecmp.cmp("/root/test/a","/root/test/a")
True
filecmp.cmpfiles(dir1,dir2,common[,shallow]),该方法返回文件名的三个列表,分别为匹配、不匹配、错误,错误列表包括目录不存在文件、不具备读写权限或其他原因导致的不能比较的文件清单