首页 > 解决方案 > Python:BadZipFile:目录和标题中的文件名不同

问题描述

我正在使用这种方法来提取这个zipfile

r = requests.get(url)
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall("Documents_zip")    #This is where the error occurs

我从 Python 得到这个错误:

BadZipFile: File name in directory '2017-08-29_Cerfa_CpC_Ombi+¿res_Lac_Th+⌐sauque.pdf' and header b'2017-08-29_Cerfa_CpC_Ombi\xc3\xa8res_Lac_Th\xc3\xa9sauque.pdf' differ.

我对 zipfile 模块不太了解,但我发现它太严格了,没有必要检查文件名和标题。

如何在不引发错误的情况下提取?

编辑 1:

我创建了这个函数以避免引发错误。它只是返回一个布尔值来指示是否运行了 zip 提取。

def download_zip(z, path):
    if not(z.testzip()):
        z.extractall(path)
        return True
    else:
        return False

标签: python-3.xzipfile

解决方案


我完成了之前的功能。它将 zip 文件提取到文件夹 namdepath中。如果出现问题,则更改当前目录的名称并指示损坏文件的数量。该函数还返回此数字。

import os
import zipfile
def download_zip(z, path):
    names_files = z.namelist()
    count = 0
    for my_file in names_files:
        if my_file:
            if z.testzip():
                if not(my_file in z.testzip()):
                    try:
                        z.extract(my_file, path=path)
                    except zipfile.BadZipfile:
                        count = count +1
            else:
                z.extract(my_file, path=path)
        else:
            count = count + 1

    if count != 0:
        my_path = os.getcwd()
        parent = os.path.dirname(my_path)
        os.chdir(parent)
        os.rename(my_path, my_path + ' - ' + str(count) + ' doc du zip non extrait')
        os.chdir(my_path + ' - ' + str(count) + ' doc du zip non extrait')
    return count

推荐阅读