Skip to content

Instantly share code, notes, and snippets.

@navono
Created June 7, 2024 00:53
Show Gist options
  • Save navono/a1115c157337c90d21f49d995952cb4e to your computer and use it in GitHub Desktop.
Save navono/a1115c157337c90d21f49d995952cb4e to your computer and use it in GitHub Desktop.
py 解压中文压缩包
def support_gbk(zip_file: zipfile.ZipFile):
name_to_info = zip_file.NameToInfo.copy()
for name, info in name_to_info.items():
try:
real_name = name.encode('cp437').decode('gbk')
except UnicodeDecodeError:
real_name = name.encode('utf-8').decode('utf-8')
if real_name != name:
info.filename = real_name
del zip_file.NameToInfo[name]
zip_file.NameToInfo[real_name] = info
return zip_file
def extract_zip(zip_filepath, extract_dir):
# 检查 ZIP 文件是否存在
if not os.path.exists(zip_filepath):
logger.error(f"The ZIP file {zip_filepath} does not exist.")
return
try:
# 创建解压缩目录(如果不存在)
clear_dir(extract_dir)
with support_gbk(zipfile.ZipFile(zip_filepath)) as zfp:
# zfp.extractall(extract_dir)
for zip_file in zfp.filelist:
member = zip_file.filename
member_path = Path(zip_file.filename)
windows_attr = zip_file.external_attr & 0xFFFF
if windows_attr & 0x10:
# 构建目标路径
member_path = Path(extract_dir) / member_path
os.makedirs(member_path)
continue
# 处理路径过长的问题
member_abs_path = Path(extract_dir) / member_path
str_member_abs_path = str(member_abs_path)
str_member_abs_path.find()
if len(str_member_abs_path) > 255:
logger.error(f"Path too long: {member_abs_path}")
continue
zfp.extract(member, extract_dir)
return pic_list
except Exception as e:
logger.error(f"Failed to extract ZIP file {zip_filepath}: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment