在Python中使用zipfile
模块解压缩大数据文件在Python 2上可以正常工作,但是在python3.6.0上会产生以下错误:
BadZipFile: Bad CRC-32 for file 'myfile.csv'
我追踪到错误处理代码检查CRC值。在
在python2上使用ZipFile.testzip()
不会返回任何结果(所有文件都很好)。在Python3上运行它会返回'myfile.csv'
,表示该文件有问题。在
要在Python2和Python3上复制的代码(需要下载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使用以下方法正确地提取文件:
^{pr2}$
与@Kundor一样,将文件大小设置为最大值(2**32-1)将有效,但对于任何大于4 GiB(4 GiB减去1字节)的文件,将其设置为ZIP64的最大大小(16 EiB减去1字节)
在(927MB压缩和11GB文件提取)上测试
CRC值正常。最新的CRC_两栖动物.csv'在zip中记录的是0x87203305。提取后,这确实是文件的CRC。在
但是,给定的未压缩大小是不正确的。压缩文件记录的压缩大小为309723024字节,未压缩大小为292198614字节(更小!)。实际上,未压缩的文件是4587165910字节(4.3gib)。这比32位计数器中断时的4 GiB阈值大。在
您可以这样修复(这至少在python3.5.2中有效):
我无法从归档文件中提取python3。一些调查结果(在macosx上)可能会有帮助。在
检查档案的运行状况
将文件设为只读,以防止意外更改:
使用
^{pr2}$zip
和unzip
检查存档:@sam mussmann也发现,
7z
报告了一个CRC错误:我的
zip
和unzip
都很老;7z
很新:摘录
使用
unzip
:使用Python 2.7.13进行提取,为简洁起见,使用
zipfile
的命令行界面:正如您所发现的,python3.6.0(也是3.4.5和3.5.2)报告了一个错误的CRC
假设1:档案包含一个错误的CRC,
zip
,unzip
并且 Python2.7.13无法检测;7z
和python3.4-3.6都在执行 没错。在假设2:存档很好;
7z
和python3.4-3.6都包含一个bug。在考虑到这些工具的相对年龄,我想H1是正确的。在
变通办法
如果您不使用Windows并且信任存档的内容,那么使用常规shell命令可能会更简单。比如:
或者您可以在Python中执行
unzip
:附带的
捕捉
ImportError
比检查 Python解释器:相关问题 更多 >
编程相关推荐