cherylgi

 


import shutil,zipfile,os


class
ToolModel(object): def dfs_get_zip_file(self,input_path, result, ignore=[]): \'\'\' 递归目录 :param input_path: 输入路径 :param result: 列表 :param ignore: 忽略文件或目录名 :return: \'\'\' files = os.listdir(input_path) for file in files: filePath = input_path + \'/\' + file if file in ignore: continue if os.path.isdir(filePath): self.dfs_get_zip_file(filePath, result, ignore) else: result.append(filePath) def zip_path(self,input_path, output_path, ignore=[]): \'\'\' :param input_path: 输入路径 /app/adminkit :param output_path: 输出路径 /app/adminkit.zip :param ignore: 忽略文件或目录名 :return: \'\'\' outdir = os.path.dirname(output_path) if not os.path.isdir(outdir): os.makedirs(outdir) f = zipfile.ZipFile(output_path, \'w\', zipfile.ZIP_DEFLATED) filelists = [] self.dfs_get_zip_file(input_path, filelists, ignore) for file in filelists: file = file.replace(\'\\\', \'/\') input_path = input_path.replace(\'\\\', \'/\') f.write(file, file.replace(input_path, \'\')) f.close() return output_path def unzip(self,filename: str,dirname): \'\'\' 解压缩 :param filename: 压缩文件名 :param dirname: 解压缩输出目录 :return: \'\'\' try: file = zipfile.ZipFile(filename) file.extractall(dirname) file.close() # 递归修复编码 self.rename(dirname) except: print(f\'{filename} unzip fail\') def rename(self,pwd: str, filename=\'\'): """压缩包内部文件有中文名, 解压后出现乱码,进行恢复""" path = f\'{pwd}/{filename}\' if os.path.isdir(path): for i in os.scandir(path): self.rename(path, i.name) newname = filename.encode(\'cp437\').decode(\'gbk\') os.rename(path, f\'{pwd}/{newname}\') def del_file(self,filepath): """ 删除指定路径下的所有文件和文件夹 :param filepath: 路径 :return: """ del_list = os.listdir(filepath) for f in del_list: file_path = os.path.join(filepath, f) if os.path.isfile(file_path): os.remove(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path)

 

分类:

技术点:

相关文章: