主页 >> 程序猿的东西 >> unzip中文乱码的python解决方法

unzip中文乱码的python解决方法

Mac下使用unzip命令解码会发现解出来的中文文件名都是乱码,这里有一种python的解压方式,我把他写成函数形式,可以开箱即用。

import os
import zipfile
import shutil
import chardet

def unzip(zipFilePath, targetDir):
    """解压zip

    Args:
        zipFilePath: zip文件
        targetDir: 目标文件夹
    """
    with zipfile.ZipFile(zipFilePath, 'r') as zf:
        for filename in zf.namelist():
            encodeInfo = chardet.detect(filename.encode('cp437'))
            print(encodeInfo)
            target_filename = targetDir+filename.encode('cp437').decode(encodeInfo['encoding'])  # 将文件名正确编码

            dirname = os.path.dirname(target_filename)
            if not os.path.exists(dirname) and dirname != "":
                os.makedirs(dirname)
            if target_filename!="" and target_filename[-1]=="/": # 文件夹
                continue

            print("Extracting:",target_filename)
            with open(target_filename, 'wb') as output_file:  # 创建并打开新文件
                with zf.open(filename, 'r') as origin_file:  # 打开原文件
                    shutil.copyfileobj(origin_file, output_file)  # 将原文件内容复制到新文件

以上代码经过python3.5测试。

根本问题是在windows下中文都是用gbk编码的,Linux或Unix下默认是UTF-8,所以这里要做一层解码。

发表评论