Python 2.7 用瑞典语Å提取zip文件ÄÖ;在python2.7中的文件名中
当我提取包含Å、Ä或Ö字母的文件的zip文件时, 我有垃圾角色。 我正在使用Python2.7Python 2.7 用瑞典语Å提取zip文件ÄÖ;在python2.7中的文件名中,python-2.7,Python 2.7,当我提取包含Å、Ä或Ö字母的文件的zip文件时, 我有垃圾角色。 我正在使用Python2.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,那么如果文件/目录名包含重音字母,则需要对其进行解码,以查看未被损
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)
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)
您在何处/何时获得垃圾字符?i、 e.当打印提取的路径、提取的邮政编码等时?您在何处/何时获得垃圾字符?i、 e.打印提取路径、提取邮政编码等时。?