标签:文件比较
# -*- coding: gbk -*- import difflib import os import time import shutil from AFALogger import LoggerError,LoggerInfor from traceback import format_exc; def compareFile(file1,file2): #比较两个文件的内容是否相同 try: file_handle_1 = open(file1) file_handle_1_read = file_handle_1.readlines() file_handle_1.close() # LoggerInfor(str(file_handle_1_read)) file_handle_2 = open(file2) file_handle_2_read = file_handle_2.readlines() file_handle_2.close() # LoggerInfor(str(file_handle_2_read)) diff = ‘‘.join(difflib.ndiff(file_handle_1_read,file_handle_2_read)) diffInfo=[] for line in diff.split(‘\n‘): if line !=‘‘: if line[0] in (‘+‘,‘-‘): diffInfo.append(line) else: continue return diffInfo except: LoggerInfor(str(file2+‘\nerror‘)) #将错误的文件写入日志,当文件名乱码的时候会出现错误 return [file2+‘\nerror‘,] def compareResultWriteFile(file2,diffInfo,resultFilename): #将不同的地方写入文件 file_handle = open(resultFilename,‘a‘) file_handle.write(file2+‘ Start\n‘) for line in diffInfo: file_handle.write(line+‘\n‘) file_handle.write(file2+‘ END\n\n‘) file_handle.close() def getAllFilename(directoryOrFilename): #在输入为目录的时候,获取目录下所有文件 allFilename=[] for name in directoryOrFilename.split(‘,‘): if os.path.isdir(name): for path,dirs,files in os.walk(name): for fn in files: allFilename.append(path+‘/‘+fn) elif os.path.isfile(name): allFilename.append(name) else: continue return allFilename def backupFile(resultDir,filename): #将本日文件备份 try: filepath_list=filename.split(‘/‘) filepath=‘_‘.join(filepath_list[3:-1]) shutil.copy(filename,resultDir+‘/‘+filepath_list[-1]+‘_‘+filepath) except: return ‘‘ def cfgCompare(sourceFile,destinationDir): ‘‘‘ @使用范例: cfgCompare(‘/home/iqms/lyb,/home/iqms/qm_info‘,‘/home/iqms/cfgDir‘) ‘‘‘ try: if not type(sourceFile) is str: return [0, "ERR001", "sourceFile参数必须为str类型", [None]]; if not type(destinationDir) is str: return [0, "ERR001", "destinationDir参数必须为str类型", [None]]; allFilename = getAllFilename(sourceFile) yesterdayDestinationDir = destinationDir+‘/‘+time.strftime(‘%Y%m%d‘,time.localtime(time.time()-24*60*60)) destinationDir = destinationDir+‘/‘+time.strftime(‘%Y%m%d‘) os.mkdir(destinationDir) for filename in allFilename: filepath_list=filename.split(‘/‘) #拼文件名 if filepath_list[-1].startswith(‘.‘): continue filepath=‘_‘.join(filepath_list[3:-1]) #拼文件名 backupFile(destinationDir,filename) if os.path.exists(yesterdayDestinationDir): # diffInfo=compareFile(yesterdayDestinationDir+‘/‘+filename.split(‘/‘)[-1],filename) # diffInfo=compareFile(yesterdayDestinationDir+‘/‘+filename.split(‘/‘)[-1],destinationDir+‘/‘+filename.split(‘/‘)[-1]) diffInfo=compareFile(yesterdayDestinationDir+‘/‘+filepath_list[-1]+‘_‘+filepath,destinationDir+‘/‘+filepath_list[-1]+‘_‘+filepath) compareResultWriteFile(filename.split(‘/‘)[-1],diffInfo,destinationDir+‘/log‘) else: continue return [1, None, None, [None]]; except Exception, e: LoggerError(str(format_exc())); return [2, ‘A015017‘, ‘异常:‘+str( e ), [None]];
标签:文件比较
原文地址:http://8588103.blog.51cto.com/8578103/1732047