1. 程式人生 > >字符串 文件 目錄對比

字符串 文件 目錄對比

diff

兩個字符串對比
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)) #兩邊都有不能比較的

字符串 文件 目錄對比