您的位置:首页 > 编程语言 > Python开发

Python使用difflib模块比较两个文件内容异同,同时输出html易浏览

2019-01-08 13:26 609 查看

因工作需求,需要对比连个文件异同,并输出html格式来对比。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import difflib

def read_file(filename):
try:
with open(filename, 'r') as f:
return f.readlines()
except IOError:
print("ERROR: 没有找到文件:%s或读取文件失败!" % filename)
sys.exit(1)

def compare_file(file1, file2, out_file):
file1_content = read_file(file1)
file2_content = read_file(file2)
d = difflib.HtmlDiff()
result = d.make_file(file1_content, file2_content)
old_str='charset=ISO-8859-1'
new_str='charset=UTF-8'
with open(out_file, 'w') as f:
f.writelines(result.replace(old_str,new_str))

if __name__ == '__main__':
compare_file(r'd:\1\a.log', r'd:\2\a.log', r'd:\result.html')

输出为一个result.html文件,打开后已于浏览。

参考:Python--比较文件内容
python使用difflib对比文件示例
Python自动化运维笔记(四):使用difflib模块实现文件内容差异对比

还有一种需要,需要手动要检测的脚本
difflib模块文件内容差异对比
源码a.py如下:(对比两个配置文件差异)

#!/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)

用法:
python a.py nginx.conf.v1 nginx.conf.v2 > sample3_diff.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐