difflib文件差異對比

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

結果:

黃色部分代表差異的部分

wKiom1kkECyzjd3GAABO0ffk1pA812.png

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

結果:

黃色部分代表差異的部分

wKioL1kkEA3jVVVuAABI3ej05Eo480.png




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章