zipfile解压乱码问题

该代码定义了一个函数defunzip_files,用于解压缩ZIP文件到指定的输出路径。它使用os和zipfile库处理文件路径和压缩内容,尝试用cp437编码解码文件名以适应不同编码格式,并创建必要的子目录来保存解压的文件。
摘要由CSDN通过智能技术生成
    def unzip_files(zip_file, output_path):
        try:
            zip_dir = os.path.splitext(os.path.basename(zip_file))[0]
            zip = zipfile.ZipFile(zip_file, 'r')
            if not os.path.isdir(output_path):
                os.makedirs(output_path)
            for each in zip.namelist():
                if not each.endswith('/'):
                    root, name = os.path.split(each)
                    try:
                        root = root.encode('cp437').decode('gbk')
                    except:
                        root = root.encode('cp437').decode('utf-8')
                    try:
                        name = name.encode('cp437').decode('gbk')
                    except:
                        name = name.encode('cp437').decode('utf-8')
                    directory = os.path.normpath(os.path.join(output_path, zip_dir, root))
                    if not os.path.isdir(directory):
                        os.makedirs(directory)
                    file = open(os.path.join(directory, name), 'wb')
                    file.write(zip.read(each))
                    file.close()
            zip.close()
        except Exception as e:
            print(str(e))

    output_path = r"C:\Users\59887\Desktop\快来解压我这里"  # Set the output path to the desired directory
    
    # Call the unzip_files function to extract the files from the zip
    unzip_files(zip_file, output_path)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值