ZipFile.testzip() 在 Python 2 和 Python 3 上返回不同的结果 [英] ZipFile.testzip() returning different results on Python 2 and Python 3

查看:133
本文介绍了ZipFile.testzip() 在 Python 2 和 Python 3 上返回不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using the zipfile module to unzip a large data file in Python works correctly on Python 2 but produces the following error on Python 3.6.0:

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

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

I traced this to error handling code checking the CRC values.

在 Python 2 上使用 ZipFile.testzip() 不返回任何结果(所有文件都正常).在 Python 3 上运行它会返回 'myfile.csv',表明该文件存在问题.

Using ZipFile.testzip() on Python 2 returns nothing (all files are fine). Running it on Python 3 returns 'myfile.csv' indicating a problem with that file.

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

Code to reproduce on both Python 2 and Python 3 (involves a 300 MB download, sorry):

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 使用以下方法正确提取文件:

Does anyone understand why this difference exists and if there's a way to get Python 3 to properly extract the file using:

archive.extract("vertnet_latest_amphibians.csv")

推荐答案

CRC 值正常.zip 中记录的vertnet_latest_amphibians.csv"的 CRC 为 0x87203305.解压后,这确实是文件的CRC.

The CRC value is OK. The CRC of 'vertnet_latest_amphibians.csv' recorded in the zip is 0x87203305. After extraction, this is indeed the CRC of the file.

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

However, the given uncompressed size is incorrect. The zip file records compressed size of 309,723,024 bytes, and uncompressed size of 292,198,614 bytes (that's smaller!). In reality, the uncompressed file is 4,587,165,910 bytes (4.3 GiB). This is bigger than the 4 GiB threshold where 32-bit counters break.

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

You can fix it like this (this worked in Python 3.5.2, at least):

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

这篇关于ZipFile.testzip() 在 Python 2 和 Python 3 上返回不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆