字符串 文件 目录对比

两个字符串对比
difflib库
例子
import difflib

text1 = '''text1:
Williams was talked out of retirement last year by his wife following a slump in form that was \
so profound that he didn't even qualify for the Crucible.
difflib document v7.4
add string'''
text1_lines = text1.splitlines() #以行分割
text2 = '''text2:
Williams was talked out of retirement last year by his wife following a slump in form that was \
so profound that he didn't even qualify for the Crucible.
difflib document v7.5'''

text2_lines = text2.splitlines()

d = difflib.Differ() #Differ函数比较字符串
diff = d.compare(text1_lines,text2_lines)
print('\n'.join(list(diff)))

#结果为

- text1:

? ^ ?号表示两个序列有增量差异,^号表示差异字符,中间的空表示两个序列一致

+ text2:

?



d = difflib.Differ() #Differ函数比较字符串
diff = d.compare(text1_lines,text2_lines)
print('\n'.join(list(diff)))
替换为下面的代码
d = difflib.HtmlDiff() #htmldiff函数将结果保存为html格式
print(d.make_file(text1_lines,text2_lines))

两个文件对比(cmp)
例子
import filecmp,sys,os
BASE_DIR = os.path.dirname(os.path.abspath(file))
d = filecmp.cmp(BASE_DIR+'\'+'nginx.conf',BASE_DIR+'\'+'nginx2.conf',shallow=False) #默认shallow为True,不比较文件内容,只比较文件基本信息(stat命令可以查看文件的基本信息)
print(d)

目录对比(dircmp)
例子
import filecmp,sys,os
BASE_DIR = os.path.dirname(os.path.abspath(file))
dir1 = '%s/%s'%(BASE_DIR,'db1')
dir2 = '%s/%s'%(BASE_DIR,'db2')

res = filecmp.dircmp(dir1,dir2,['nginx.conf']) #方括号中的表示忽略
res.report() #比较指定目录
res.report_partial_closure()#比较指定目录以及第一级目录
res.report_full_closure()#递归比较所有指定目录

print('left_list:'+str(res.left_list)) #左目录列表
print('right_list:'+str(res.right_list))#右目录列表
print('common:'+str(res.common))#两个目录共同的
print('left_only:'+str(res.left_only))#仅在左目录
print('right_only:'+str(res.right_only))#仅在右目录
print('common_dirs:'+str(res.common_dirs))#两边都有的子目录
print('common_files:'+str(res.common_files))#两边都有的子文件
print('common_funny:'+str(res.common_funny))
print('same_files:'+str(res.same_files)) #匹配相同的
print('diff_files:'+str(res.diff_files)) #不匹配的
print('funny_files:'+str(res.funny_files)) #两边都有不能比较的

猜你喜欢

转载自blog.51cto.com/xiaoshanzi/2119092