python-2.7 - 在python2.7的文件名中提取带有瑞典语ÅÄÖ的zip文件
问题描述
当我提取包含带有 Å、Ä 或 Ö 字母的文件的 zip 文件时,我得到了垃圾字符。我使用python 2.7。
with zipfile.ZipFile(temp_zip_path.decode('utf-8')) as f:
for fn in f.namelist():
extracted_path = f.extract(fn)
解决方案
Zipfile 假定文件名的编码是 CP437。如果您的 zipfile 编码不是 unicode,则需要对包含重音字母的文件/目录名称进行解码才能看到非垃圾名称。但是,如果您尝试根据解码后的字符串提取内容,它将找不到,因为 zipfile 会按原始(垃圾或非垃圾)名称查找内容。
您可以在提取后一个一个地重命名文件,但这会很痛苦。
你可以做的是这样的:读取内容并将它们写在解码的名称上。
# -*- coding: utf-8 -*-
import zipfile
import os
temp_zip_path = r'd:\Python_projects\sandbox\cp_437.zip'
temp_zip_path2 = r'd:\Python_projects\sandbox\unicode.zip'
target_loc = os.path.dirname(os.path.realpath(__file__))
def unpack_cp437_or_unicode(archive_path):
with zipfile.ZipFile(archive_path) as zz:
for zipped_name in zz.namelist():
try:
real_name = zipped_name.decode('cp437')
except UnicodeEncodeError:
real_name = zipped_name
with zz.open(zipped_name) as archived:
contents = archived.read()
if zipped_name.endswith('/'):
dirname = os.path.join(target_loc, real_name)
if not os.path.isdir(dirname):
os.makedirs(dirname)
else:
with open(os.path.join(target_loc, real_name), 'wb') as target:
target.write(contents)
unpack_cp437_or_unicode(temp_zip_path)
unpack_cp437_or_unicode(temp_zip_path2)
推荐阅读
- prolog - Prolog 可调用预期发现整数错误
- java - 更新导航抽屉中当前突出显示的片段
- c - 通过引用而不是指向缓冲区的指针传递结构的转换问题
- docker - 在 Docker 中托管的 .NET Core 控制台应用程序中使用环境变量
- nginx - 重写 Nginx 不起作用
- python - 如何自定义刻度?
- html - 格式化表单域
- r - Reshape data wide-to-long, preserve variable order in `varying`
- javascript - 在 .each 函数中等待 $.ajax 结果
- python - 加载具有自定义注意层的 keras 模型时出现未知层错误