Python使用 zipfile模块解压包含多路径中文文件名的zip包(基于Windows下验证)

本文介绍了解决zip压缩包在解压时中文文件名出现乱码的问题,核心在于正确的文件名编码格式。文章解释了zip包使用CP437编码,以及如何通过编解码操作避免乱码,提供了具体实现代码。

zip包中中文名解压是出现乱码的核心是文件名编码格式不正确。

官方释疑:


There is no official file name encoding for ZIP files. If you have unicode file names, you must convert them to byte strings in your desired encoding before passing them to write(). WinZip interprets all file names as encoded in CP437, also known as DOS Latin.
 


zip包文件名会用CP437来编码,因此需要相应的编解码操作来避免乱码。因此不用ZipFile.extract(member[, path[, pwd]]),需用shutil进行数据内容的拷贝,这样就解决了压缩包下中文多路径解压乱码问题。

实现代码如下:

 

import zipfile
import shutil

def unzip_each_zip_package(fn):
    try:
        if zipfile.is_zipfile(fn):
            zf = zipfile.ZipFile(fn)
            for fName in zf.namelist():
                correct_fn = fName.encode('cp437').decode('gbk') #这里就用来编解码的操作的
                if not os.path.exists(correct_fn) and str(correct_fn).endswith("/"): #判断文件路径是否存在
                    os.makedirs(correct_fn) #没有文件路径的创建文件路径
                else:
                    with open(right_fn, 'wb') as disfile: #创建相应文件
                        with zf.open(fName, 'r') as srcfile:
                            shutil.copyfileobj(srcfile, disfile)
    except Exception as error:
        print(error)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值