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

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)

 

你可能感兴趣的:(python,Django)