当前第2页 返回上一页
示例
1 2 3 4 5 6 7 8 9 10 11 | >>> diff = ndiff( 'one\ntwo\nthree\n' .splitlines( 1 ),
... 'ore\ntree\nemu\n' .splitlines( 1 ))
>>> diff = list (diff)
>>> print ''.join(restore(diff, 1 )),
one
two
three
>>> print ''.join(restore(diff, 2 )),
ore
tree
emu
|
difflib.unified_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm])
比较a与b(字符串列表),返回一个unified diff格式的差异结果.
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> s1 = [ 'bacon\n' , 'eggs\n' , 'ham\n' , 'guido\n' ]
>>> s2 = [ 'python\n' , 'eggy\n' , 'hamster\n' , 'guido\n' ]
>>> for line in unified_diff(s1, s2, fromfile = 'before.py' , tofile = 'after.py' ):
... sys.stdout.write(line)
- - - before.py
+ + + after.py
@@ - 1 , 4 + 1 , 4 @@
- bacon
- eggs
- ham
+ python
+ eggy
+ hamster
guido
|
实际应用示例
比对两个文件,然后生成一个展示差异结果的HTML文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import difflib
hd = difflib.HtmlDiff()
loads = ''
with open ( 'G:/python/note/day09/0907code/hostinfo/cpu.py' , 'r' ) as load:
loads = load.readlines()
load.close()
mems = ''
with open ( 'G:/python/note/day09/0907code/hostinfo/mem.py' , 'r' ) as mem:
mems = mem.readlines()
mem.close()
with open ( 'htmlout.html' , 'a+' ) as fo:
fo.write(hd.make_file(loads,mems))
fo.close()
|
运行结果:

生成的html文件比对结果:

以上就是python difflib模块详解的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
Python 列表推导式使用注意事项
了解Python的collections.counter类型
读懂Python的异常机制
Python列表和元组的相同点和不同点是什么
pip Python库安装在哪里了
a[1:]在Python什么意思
在不同的Python版本中,不换行输出有什么变化?
Python比较两浮点数是否相等的方法
详谈Python在windows中的文件路径问题
Python调用xlsxwriter创建xlsx的方法
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python difflib模块详解