文件差异对比
示例一:
#coding:utf-8import difflib
text1 = ‘‘‘1. Beautiful is better than ugly.
2. Explicit is better than implicit.
3. Simple is better than complex.
4. Complex is better than complicated.‘‘‘.splitlines(1)
text2 = ‘‘‘1. Beautiful is better than ugly.
3. Simple is better than complex.
4. Complicated is better than complex.
5. Flat is better than nested.‘‘‘.splitlines(1)
# 创建diff对象
d=difflib.Differ()
# 采用compare方法对字符串进行比较for i in d.compare(text1,text2):
print i
执行结果:
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))
参数:
‘-‘ 包含在第一个中,但不包含在第二个中
‘+‘ 包含在第二个中,但不包含在第一个中
‘‘ 两者相同
‘?‘ 两个存在增量差异
‘^‘ 标志出两者行存在的差异字符
示例二:
#coding:utf-8import difflib
text1 = ‘‘‘1. Beautiful is better than ugly.
2. Explicit is better than implicit.
3. Simple is better than complex.
4. Complex is better than complicated.‘‘‘.splitlines(1)
text2 = ‘‘‘1. Beautiful is better than ugly.
3. Simple is better than complex.
4. Complicated is better than complex.
5. Flat is better than nested.‘‘‘.splitlines(1)
d=difflib.HtmlDiff()print d.make_file(text1,text2)
执行结果:
[vaon@station Desktop]$ python diff_file.py >/home/vaon/Desktop/diff_file.html
执行完之后桌面上会生成一个html文件,用浏览器打开就可以直观的看到两个文件的不同:
原文:https://www.cnblogs.com/vaon/p/11198251.html