python-3.x - 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
解决方案
我完成了之前的功能。它将 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
推荐阅读
- linux - npm install 失败并显示 npm.cmd: command not found
- c# - 如何过滤 XML 文档中的 XML 节点及其子节点?
- javascript - 尝试替换动态元素的值
- hyperlink - 如何在 JasperStudio 的 TextField 中仅在某些单词上放置超链接?
- windows-10 - 什么是 Windows 10 中的受管端口排除?
- amazon-web-services - 如何在 buildspec.yaml 中检索 Secret Manager 数据
- jquery - 我如何向除前四个项目之外的所有项目添加类
- excel - 未找到 VBA 点。重点在图片中
- github - 是否有任何选项可用于在只有有限存储库访问的 Azure Devops 上创建服务连接?
- laravel-5 - 更新了数据库中的图像存储,但不是 laravel 中的文件夹