Python文件对比

环境:

python2.6.6

linux系统



对比文件差异用Python里的difflib模块:

Python自带difflib模块,无需安装。


对比两个文件是否一样总体思路就是:将文件里的内容读出来然后再对比


符号 含义
+ 包含在第二个序列中,但不包含第一个序列中
- 包含在第一个序列中,但不包含第二个序列中
标志两个序列行存在增量差异
^ 标志两个序列存在的差异字符
'' 两个序列行一致

示例一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/python
#coding:utf-8
#2017,8,27
 
import difflib
 
text1='''1234567890
this is a text one.
heihiehie
'''
text1_line=text1.splitlines() #以行进行分割,以便以后对比
 
text2='''235678956545
This is a Text two.
heiheihei
'''
text2_line=text2.splitlines()
 
= difflib.Differ() #创建Differ()对象
 
diff = d .compare(text1_line,text2_line)
 
print '\n'.join(list(diff))

看下运行结果:


Python文件对比


都是符号,符号不好分辨,接下来生成html文件。


示例二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/python
#coding:utf-8
#2017,8,27
 
 
import difflib
 
text1='''1234567890
this is a text one.
heihiehie
'''
 
text1_line=text1.splitlines() #以行进行分割,以便以后对比
 
text2='''235678956545
This is a Text two.
heiheihei
'''
 
text2_line=text2.splitlines()
= difflib.HtmlDiff() #创建Differ()对象
print d.make_file(text1_line,text2_line)

执行命令生成diff.html文件

1
[[email protected] difflib]# python diff_simple2.py >> diff.html

用浏览器打开diff.html文件:

Python文件对比


这样是不是就好看多了。


综合应用,对比两个文件的差异:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/python
#-*-coding:utf-8-*-
#2017.9.5
 
import difflib
import sys
 
#接收参数
try:
    textfile1=sys.argv[1]
    textfile2=sys.argv[2]
 
except Exception,e:
    print "error:"+str(e)
    print "usage:python Contrast_file.py filename1 filename2 >> diff.html"
    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:python Contrast_file.py filename1 filename2 >> diff.html" 
    sys.exit()
#调用函数获取分割后的字符串
text1_lines = readfile(textfile1)  
text2_lines = readfile(textfile2)
 
#创建html类对象,并且进行比较。
diff = difflib.HtmlDiff()
print diff.make_file(text1_lines,text2_lines)

执行命令生成diff2.html文件,用浏览器打开和示例二一样。

1
[[email protected] difflib]# python Contrast_file.py httpd.conf httpd.conf.bak >> diff2.html

参考资料:网络和Python自动化运维技术与最佳实践

总结:思路很重要,这次文件对比的思路就是先把文件读出来,在进行对比。每天进步一点点。



Python文件对比



本文转自 天道酬勤VIP 51CTO博客,原文链接:http://blog.51cto.com/tdcqvip/1962936