python zip压缩文件、文件夹 作者:马育民 • 2024-04-29 11:34 • 阅读:10063 ``` import os,zipfile class ZipFileUtil: def __init__(self,zip_file_path): self.zip_path = zip_file_path self.f = zipfile.ZipFile(zip_file_path, 'w',zipfile.ZIP_DEFLATED) def zip_file(self,src_path): ''' 压缩文件 :param zip_path: 压缩包路径 :param src_path: 要压缩的文件路径,可以是 str :return: ''' name = os.path.basename(src_path) self.f.write(src_path,name) def zip_dir(self,src_path): ''' 压缩目录 :return: ''' src_folder = os.path.basename(src_path) sep = os.path.sep # 是否第一层,如果第一层,且空目录,压缩时不设置父目录;如果不是第一层,且空目录,压缩时要有父目录 is_first = True # 目录的压缩包 for (archiveDirPath, dirNames, fileNames) in os.walk(src_path): for fileName in fileNames: file_path = os.path.join(archiveDirPath, fileName) name_temp = file_path.replace(src_path, "") self.f.write(file_path, src_folder+sep+name_temp) # 包含空目录 if not fileNames and not dirNames: name_temp = os.path.basename(archiveDirPath) if is_first: zip_info = zipfile.ZipInfo(name_temp + "/") else: zip_info = zipfile.ZipInfo(src_folder+sep+name_temp + "/") self.f.writestr(zip_info, "") is_first = False def close(self): self.f.close() if __name__ == "__main__": zip_path = r'E:\abc2.zip' if os.path.exists(zip_path): os.remove(zip_path) zipObj = ZipFileUtil(zip_path) zipObj.zip_dir(r'E:\啊啊啊32') zipObj.zip_file(r'E:\2.txt') zipObj.close() ``` 原文出处:http://malaoshi.top/show_1IX7b7Kd8PUv.html