标签:python
#############difflib##############
文件差异对比
示例1:
import difflib
text1 = ‘hello westos‘
text2 = ‘hello zhan‘
text1_lines = text1.splitlines()
text2_lines = text2.splitlines()
# 创建diff对象
d = difflib.Differ()
# 采用compare方法对字符串进行比较
diff = d.compare(text1_lines, text2_lines)
# print list(diff)
print ‘\n‘.join(list(diff))
text1=‘‘‘root:x:0:wfew0:root:/root:/bin/bash
bin:x:1fw:1:bin:/bin:/sbwefwin/nologin
daemon:xw:2:2:daefwmon:/sbin:/sbin/nologin
adm:x:3:4:adwfwfm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
synsfwfsc:x:5:0:sync:/sbin:/bin/sync
shautdowfwfwn:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
‘‘‘
text2=‘‘‘rot:x:0:0:root:/root:/bin/bash
bin:x:1:1:bi:/bin:/sbin/nologindaem
on:x:2:2:daemon:/sbin:/sbin/login
adm:x:3:4:adm:var/adm:/sbin/nolog
lp:x:4:7:lp:/var/spool/lpd:/sbin/nolo
gisync:x:5:0:sync:/sbin:/bin/sync
utdown:x:6:0:shtdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
‘‘‘
第一种方法
import difflib
text1_lines=text1.splitlines()
text2_lines=text2.splitlines()
d=difflib.Differ()
a=d.compare(text1_lines,text2_lines)
a=list(a)
print ‘\n‘.join(a)
测试:
第二种方法
import difflib
text1_lines=text1.splitlines()
text2_lines=text2.splitlines()
# d=difflib.Differ()
# a=d.compare(text1_lines,text2_lines)
# a=list(a)
# print ‘\n‘.join(a)
d=difflib.HtmlDiff()
htmldata=d.make_file(text1_lines,text2_lines)
with open(‘/root/Desktop/data.html‘,‘a+‘) as f:
f.write(htmldata)
测试:
文件差异对比
‘-‘ 包含在第一个中,但不包含在第二个中
‘+‘ 包含在第二个中,但不包含在第一个中
‘ ‘ 两者相同
‘?‘ 两个存在增量差异
‘^‘ 标志出两者行存在的差异字符
标签:python
原文地址:http://12920735.blog.51cto.com/12910735/1951245