首页 > 解决方案 > 在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)

标签: python-2.7

解决方案


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)

推荐阅读