Python解压含DEFLATE64压缩的Zip文件报错,求解决方案
如何在Python 3.x中解压使用DEFLATE64(压缩方法9)的Zip文件?
我有一个Zip文件,双击Finder打开时会报错“Error - 79 Inappropriate file type or format”,但在Mac终端执行以下命令可正常解压:
unzip zip_file.zip > extracted.txt
最终目标是用Python 3.x解压该文件,已尝试以下方法均失败:
使用py7zr模块:
with py7zr.SevenZipFile(fq_file_name, mode='r') as archive: archive.extractall(file_path)报错:
raise Bad7zFile("not a 7z file") py7zr.exceptions.Bad7zFile: not a 7z file使用zipfile模块:
with zipfile.ZipFile(fq_file_name, 'r') as zip_ref: zip_ref.extractall(file_path)报错:
raise NotImplementedError("That compression method is not supported") NotImplementedError: That compression method is not supported使用shutil模块:
shutil.unpack_archive(fq_file_name)报错:
NotImplementedError: That compression method is not supported
查看zipfile模块源码后确认,失败原因是该文件使用了不支持的压缩方法9(即DEFLATE64)。
解决方法
方法1:调用系统的unzip命令(最简便)
既然终端的unzip命令能正常解压,直接在Python中通过subprocess模块调用该命令即可,示例代码:
import subprocess import os def extract_deflate64_zip(zip_path, extract_dir): # 确保解压目录存在 os.makedirs(extract_dir, exist_ok=True) # 调用系统unzip命令 result = subprocess.run( ['unzip', zip_path, '-d', extract_dir], capture_output=True, text=True ) if result.returncode == 0: print("解压成功") else: print(f"解压失败,错误信息:{result.stderr}") # 使用示例 extract_deflate64_zip("zip_file.zip", "./extracted")
方法2:使用支持DEFLATE64的第三方库
使用zipfile-deflate64库,它是标准zipfile模块的扩展,原生支持DEFLATE64压缩方法。
- 安装库:
pip install zipfile-deflate64
- 解压代码(和标准zipfile用法一致):
import zipfile_deflate64 as zipfile with zipfile.ZipFile("zip_file.zip", 'r') as zip_ref: zip_ref.extractall("./extracted")
内容的提问来源于stack exchange,提问作者Bitmask
相关产品推荐
相关产品推荐

