#!/usr/bin/env python #_*_encoding:utf-8 # 2018/05/29 #augustyang #2.0 ''' 解压文件,合并文件 打包成zip格式文件 生成MD5值 ''' import zipfile import os import shutil import time import hashlib file_dir= r"C:UsersaugustDesktop新建文件夹 (3)" slice1 = slice(0,2) #取2级文件夹 ll_test = [] #存放解压好的各层子目录 [['release'], ['HotfixRoot'], ['Gamei'], ['2.90'], ['Iphone'], []] def Get_address(file_dir): #获取每个zip文件的绝对地址 list_1 = [] for root, dirs, files in os.walk(file_dir): for fn in files: if fn.endswith(".zip"): list_1.append(file_dir+os.sep+fn) return list_1 def un_zip(file_name): #解压zip文件 """unzip zip file""" zip_file = zipfile.ZipFile(file_name) if os.path.isdir(file_name+'_files'): pass else: os.mkdir(file_name+'_files') for names in zip_file.namelist(): zip_file.extract(names, file_name + "_files/") zip_file.close() return (file_name +'_files') #找到解压的目录 def func(dir): list_1 = [] for root, dirs, files in os.walk(dir): list_1.append(dirs) return os.path.join(file_dir,list_1[0][0]) def mk_dir(dir): #创建slice1层文件夹 for root, dirs, files in os.walk(dir): ll_test.append(dirs) test1 = '' for i in ll_test[slice1]: test1 = os.path.join(test1,i[0]) dir_name = test1 + '\' return dir_name def copytree(src, dst, symlinks=False, ignore=None): #合并文件 for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) def rm_dirs(path): #删除目录 ls = os.listdir(path) for i in ls: c_path = os.path.join(path,i) if os.path.isdir(c_path): if shutil.rmtree(c_path) == None: print ('删除成功') def archive_file_zip(source_dir, output_filename): #打包成zip包 zipf = zipfile.ZipFile(output_filename, 'w') pre_len = len(os.path.dirname(source_dir)) for parent, dirnames, filenames in os.walk(source_dir): for filename in filenames: pathfile = os.path.join(parent, filename) arcname = pathfile[pre_len:].strip(os.path.sep) zipf.write(pathfile, arcname) zipf.close() def GetFileMd5(filename): #产生MD5值 if not os.path.isfile(filename): return myhash = hashlib.md5() f = open(filename,'rb') while True: b = f.read(1024) if not b : break myhash.update(b) f.close() return myhash.hexdigest() if __name__ =="__main__": rm_dirs(file_dir) l_list = [] for i in Get_address(file_dir): old_filename = un_zip(i) l_list.append(old_filename) ll = mk_dir(func(file_dir)) #创建slice1层文件夹 for i in l_list: copytree(i+'\'+ll,file_dir+'\'+ll) now_time = time.strftime("%Y_%m_%d_%H_%M",time.localtime()) #时间 file_dir_zip = ll.split(os.sep)[0] file_name = 'kitty_client_CDN_'+now_time+'.zip' archive_file_zip(os.path.join(file_dir,file_dir_zip),os.path.join(file_dir,file_name)) print(file_name,'MD5值为:',GetFileMd5(os.path.join(file_dir,file_name)))
删除成功 删除成功 删除成功 kitty_client_CDN_2018_05_29_20_17.zip MD5值为: f2409e4f802eb82a1fd118ca6b76b866