码迷,mamicode.com
首页 > 其他好文 > 详细

difflib文件差异对比

时间:2017-05-23 21:44:47      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:document   python   comparing   classes   provides   

1、两个字符串差异对比:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import difflib
text1 = ‘‘‘text1:
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.4
add string
‘‘‘
text1_lines = text1.splitlines()
text2 = ‘‘‘text2:
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.5
add string
‘‘‘
text2_lines = text2.splitlines()
d = difflib.Differ()
diff = d.compare(text1_lines,text2_lines)
print ‘\n‘.join(list(diff))

结果:
[root@localhost test]# python a3.py 
- text1:
?     ^

+ text2:
?     ^

  This module provides classes and functions for comparing sequences.
  including HTML and context and unified diffs.
- difflib document v7.4
?                     ^

+ difflib document v7.5
?                     ^

  add string
[root@localhost test]#

2、生成HTML格式对比:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import difflib
text1 = ‘‘‘text1:
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.4
add string
‘‘‘
text1_lines = text1.splitlines()
text2 = ‘‘‘text2:
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.5
add string
‘‘‘
text2_lines = text2.splitlines()
d = difflib.HtmlDiff()
print d.make_file(text1_lines,text2_lines)

python a3.py > diff.html

结果:

黄色部分代表差异的部分

技术分享

3、对比文件差异:
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import difflib
import sys
try:
    textfile1 = sys.argv[1]
    textfile2 = sys.argv[2]
except Exception,e:
    print "Error:" + str(e)
    print "Usage: a3.py filename1 filename2"
    sys.exit()
def readfile(filename):
    try:
        fileHandle = open(filename,‘rb‘)
        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: a3.py filename1 filename2"
    sys.exit()
text1_lines = readfile(textfile1)
text2_lines = readfile(textfile2)
d = difflib.HtmlDiff()
print d.make_file(text1_lines,text2_lines)

python a3.py install.log installl.log > diff2.html

结果:

黄色部分代表差异的部分

技术分享




本文出自 “gswcfl” 博客,请务必保留此出处http://guoshiwei.blog.51cto.com/2802413/1928752

difflib文件差异对比

标签:document   python   comparing   classes   provides   

原文地址:http://guoshiwei.blog.51cto.com/2802413/1928752

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!