python - ZipFile.testzip() 在 Python 2 和 Python 3 上返回不同的结果

标签 python python-3.x python-2.x unzip python-zipfile

在 Python 中使用 zipfile 模块解压缩大型数据文件在 Python 2 上可以正常工作,但在 Python 3.6.0 上会产生以下错误:

BadZipFile:文件“myfile.csv”的错误 CRC-32

我将其追溯到检查 CRC 值的错误处理代码。

在 Python 2 上使用 ZipFile.testzip() 不会返回任何结果(所有文件都很好)。在 Python 3 上运行它返回 'myfile.csv' 表示该文件有问题。

在 Python 2 和 Python 3 上重现的代码(涉及 300 MB 下载,抱歉):

import zipfile
import urllib
import sys

url = "https://de.iplantcollaborative.org/anon-files//iplant/home/shared/commons_repo/curated/Vertnet_Amphibia_Sep2016/VertNet_Amphibia_Sept2016.zip"

if sys.version_info >= (3, 0, 0):
    urllib.request.urlretrieve(url, "vertnet_latest_amphibians.zip")
else:
    urllib.urlretrieve(url, "vertnet_latest_amphibians.zip")

archive = zipfile.ZipFile("vertnet_latest_amphibians.zip")
archive.testzip()

有谁知道为什么存在这种差异,以及是否有办法让 Python 3 使用以下方法正确提取文件:

archive.extract("vertnet_latest_amphibians.csv")

最佳答案

CRC 值正常。 zip 中记录的“vertnet_latest_amphibians.csv”的 CRC 是 0x87203305。提取后,这确实是文件的CRC。

但是,给定的未压缩大小不正确。 zip 文件记录了 309,723,024 字节的压缩大小和 292,198,614 字节的未压缩大小(更小!)。实际上,未压缩的文件为 4,587,165,910 字节 (4.3 GiB)。这大于 32 位计数器中断的 4 GiB 阈值。

您可以像这样修复它(至少在 Python 3.5.2 中有效):

archive = zipfile.ZipFile("vertnet_latest_amphibians.zip")
archive.getinfo("vertnet_latest_amphibians.csv").file_size += 2**32
archive.testzip() # now passes
archive.extract("vertnet_latest_amphibians.csv") # now works

关于python - ZipFile.testzip() 在 Python 2 和 Python 3 上返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41492984/

相关文章:

python - colorSliderGrp 和 setAttr 之间的链接

python - Python 3.6 的最新 Anaconda 包可以用于 Python 3.5 吗?

python - 在 Jupyter Notebook 中嵌入幻灯片

python - 对于要在虚拟环境和非虚拟环境中运行的 Python 3 脚本,应使用什么 shebang?

c++ - 在 C++ 中使用 cURL 和多线程

python - 如何存储非英文文本?

python-2.x - 如何防止 pexpect 回显密码?

python - 值错误: Row or column values must be at least 1 when using OpenPyXl

python - BS4 : How would I remove unncessary html tags and only keep the <p> and <ruby> tags?

python - 如何修复“Python 返回方法不返回串联字符串中的整数