# -*- coding: utf-8 -*- import os import shutil import time import zipfile class Unzip(object): def __init__(self, zip_package_name, extract_path): # 待解压包名 self.zip_package_name = zip_package_name # 解压路径 self.extract_path = extract_path # 临时文件夹 self.extract_path_temp = extract_path + r"_" def unzip_exec(self): # 如果临时文件夹存在则删除 try: shutil.rmtree(self.extract_path_temp) except: pass else: while True: if os.path.exists(self.extract_path_temp): time.sleep(1) else: break # 压缩包对象 zip_file = zipfile.ZipFile(self.zip_package_name) # 解压所有文件至临时目录 zip_file.extractall(self.extract_path_temp) zip_file.close() def move_files_to_extract_path(self): # 临时文件夹中文件复制至解压目录 self.copy_dirs(self.extract_path_temp, self.extract_path) time.sleep(1) # 删除临时目录 shutil.rmtree(self.extract_path_temp) def copy_dirs(self, from_, to_): """复制目录下所有文件及子目录""" # 目标目录不存在则新建 if not os.path.exists(to_): os.makedirs(to_) # 源目录下文件列表 from_file_list = os.listdir(from_) for file in from_file_list: # 如果列表中的文件为文件则复制至目标目录 if os.path.isfile(os.path.join(from_, file)): shutil.copy(os.path.join(from_, file), os.path.join(to_, file)) # 如果列表中的文件为目录则调用函数自身递归 else: self.copy_dirs(os.path.join(from_, file), os.path.join(to_, file)) def anti_garbled_code(self, extract_path): # os.chdir(dir_names) for file_name in os.listdir(extract_path): # 使用cp437对文件名进行解码还原 file_name_temp = file_name.encode('cp437') # win下一般使用的是gbk编码 file_name_gbk = file_name_temp.decode("gbk") # 对乱码的文件名及文件夹名进行重命名 file_path = os.path.join(extract_path, file_name) file_path_gbk = os.path.join(extract_path, file_name_gbk) os.rename(file_path, file_path_gbk) # 传回重新编码的文件名给原文件名 file_name = file_name_gbk # 子文件夹/文件路径 sub_path = os.path.join(extract_path, file_name) if os.path.isdir(sub_path): # 如果是子文件夹调用函数自身递归 self.anti_garbled_code(sub_path) def run(self): self.unzip_exec() self.anti_garbled_code(self.extract_path_temp) self.move_files_to_extract_path() if __name__ == '__main__': unzip = Unzip(r"d:\test.zip", r"d:\test1") unzip.run()