python difflib_python---difflib

文件内容差异对比

difflib为python的标准库模块,无需安装。作用时对比文本之间的差异。并且支持输出可读性比较强的HTML文档,与LInux下的diff 命令相似。在版本控制方面非常有用。

#!/usr/bin/env python

# -*- coding:utf-8 -*-

#Author: 小祎

import difflib

text1 = """ #定义字符串1

user www www;

worker_processes 2;

error_log logs/error.log;

#error_log logs/error.log notice;

#error_log logs/error.log info;

pid logs/nginx.pid;

events {

use epoll;

worker_connections 2048;

}

http {

include mime.types;

default_type application/octet-stream;

server {

listen 80;

server_name itoatest.example.com;

root /apps/oaapp;

charset utf-8;

access_log logs/host.access.log main;

"""

text1_lines = text1.splitlines() #以行进行分割

text2 = """ #定义字符串2

user www www;

worker_processes 2;

error_log logs/error.log;

#error_log logs/error.log notice;

#error_log logs/error.log info;

pid logs/nginx.pid;

events {

use epoll;

worker_connections 2000;

}

http {

include mime.types;

default_type application/octet-stream;

server {

listen 80;

server_name itoatest.example.com;

root /apps/oaapp;

charset utf-8;

access_log logs/host.access.log main;

"""

text2_lines = text2.splitlines()

d = difflib.Differ()#创建Differ对象

diff = d.compare(text1_lines,text2_lines)

print('\n'.join(list(diff)))

符号

含义

'-'

包含在第一个系列行中,但不包含第二个。

'+'

包含在第二个系列行中,但不包含第一个。

' '

两个系列行一致

'?'

存在增量差异

'^'

存在差异字符

生成对比HTML格式 文档

使用HtmlDiff()类的make_file()方法生成HTML文档

#对上面代码修改

# d = difflib.Differ()#创建Differ对象

# diff = d.compare(text1_lines,text2_lines)

# print('\n'.join(list(diff)))

d = difflib.HtmlDiff()

print(d.make_file(text1_lines,text2_lines))

python xxx.py > diff.html

对比Nginx配置文件差异脚本

#!/usr/bin/env python3

# -*- coding:utf-8 -*-

#Author: guhf

import difflib

import string

import sys

try:

textfile1 = sys.argv[1]

textfile2 = sys.argv[2]

except Exception:

print("Error:" + str(e))

print("Usage: xxxx.py filename1 filename2")

sys.exit()

def readfile(filename):

try:

fileHandle = open(filename,'r')

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)

d = difflib.HtmlDiff()

print(d.make_file(text1_lines,text2_lines))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值