python difflib模块对比文件内容差异

发布时间:2020-08-30编辑:脚本学堂
在python代码中用difflib模块比较文件内容的不同,两个字符串的差异对比,对比nginx配置文件差异,实例学习difflib模块用法。

python监控difflib模块,对比文件内容差异

1、两个字符串的差异对比
 

复制代码 代码示例:
#!/usr/bin/env python
#
import difflib
text1 = """text1:
This module provides classes and functions for comparing sequences.
including HTML and context and unifled diffs.
difflib documnet v7.4
add string
"""
text1_line = text1.splitlines()
text2 = """text2:
This module provides classes and functions for Comparing sequences.
including HTML and context and unified diffs.
difflib documnet v7.5"""
text2_line = text2.splitlines()
d = difflib.Differ()
diff = d.compare(text1_line,text2_line)
print 'n'.join(list(diff))

生成美观的对比html格式文件:
 

d = difflib.HtmlDiff()
print d.make_file(text1_line,text2_line)

运行:
 

python test.py > diff.html

2、对比nginx配置文件差异
 

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

try:
textfile1 = sys.argv[1]
textfile2 = sys.argv[2]
except Exception,e:
print "Error:" + str(e)
print "Usage: test.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:test.py filename1 filename2"
sys.exit()

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