当前第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可变对象和不可变对象
Python怎么创建一维数组
Python 通过字符串调用对象属性或方法
Python中关于日期加减法的操作详解
Python的变量类型-列表的操作与截取(实战与分析)
Python内置模块collections介绍
Python代码运行结果的显示
Python有什么好书推荐
Python怎么获取二维矩阵的单行每列最大值
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python difflib模块详解