以静默方式打开不支持的压缩类型的zipfile将返回空的文件流,而不是引发异常

2024-04-19 11:13:09 发布

您现在位置:Python中文网/ 问答频道 /正文

似乎是在敲掉我的头一个新手的错误,我不是一个新手。 我有一个1.2G已知良好的zip file'train.zip'包含一个3.5G文件'train.csv'。 我打开zipfile并文件本身没有任何异常(noLargeZipFile),但生成的文件流似乎是空的。(UNIX'unzip-c…'确认它是好的) Python ZipFile.open()返回的文件对象不是seek或tell,因此我无法检查。

Python发行版是2.7.3epd free 7.3-1(32位);但对于大型zip应该是可以的。操作系统是MacOS 10.6.6

import csv
import zipfile as zf

zip_pathname = os.path.join('/my/data/path/.../', 'train.zip')
#with zf.ZipFile(zip_pathname).open('train.csv') as z:
z = zf.ZipFile(zip_pathname, 'r', zf.ZIP_DEFLATED, allowZip64=True) # I tried all permutations
z.debug = 1
z.testzip() # zipfile integrity is ok

z1 = z.open('train.csv', 'r') # our file keeps coming up empty?

# Check the info to confirm z1 is indeed a valid 3.5Gb file...
z1i = z.getinfo(file_name)
for att in ('filename', 'file_size', 'compress_size', 'compress_type', 'date_time',  'CRC', 'comment'):
    print '%s:\t' % att, getattr(z1i,att)
# ... and it looks ok. compress_type = 9 ok?
#filename:  train.csv
#file_size: 3729150126
#compress_size: 1284613649
#compress_type: 9
#date_time: (2012, 8, 20, 15, 30, 4)
#CRC:   1679210291

# All attempts to read z1 come up empty?!
# z1.readline() gives ''
# z1.readlines() gives []
# z1.read() takes ~60sec but also returns '' ?

# code I would want to run is:
reader = csv.reader(z1)
header = reader.next()
return reader

Tags: 文件csvsizeistrainopenzipcompress
3条回答

是否可能文件太大,python无法在内存中提取?当train.csv较小时是否有效?

您可以尝试使用类似于此处所示的方法来读取:How do you unzip very large files in python?

我处理Python的ZipFile不支持的压缩类型的解决方案是在ZipFile.extractall失败时依赖对7zip的调用。

from zipfile import ZipFile
import subprocess, sys

def Unzip(zipFile, destinationDirectory):
    try:
        with ZipFile(zipFile, 'r') as zipObj:
            # Extract all the contents of zip file in different directory
            zipObj.extractall(destinationDirectory)
    except:
        print("An exception occurred extracting with Python ZipFile library.")
        print("Attempting to extract using 7zip")
        subprocess.Popen(["7z", "e", f"{zipFile}", f"-o{destinationDirectory}", "-y"])

原因是:

  • 此文件的压缩类型是类型9:Deflate64/Enhanced Deflate(PKWare的专有格式,而不是更常见的类型8)
  • 还有一个zipfile错误:它不会对不支持的压缩类型抛出异常。它过去只是silently return a bad file object[第4.4.5节压缩方法]。奥尔。多假啊。我提交了那个bug,现在当压缩类型未知时它会引发NotImplementedError。

一个命令行解决方法是解压缩,然后重新压缩,得到一个普通的类型8:Deflated

zipfile will throw an exception in 2.7,3.2+出于法律原因,我想zipfile永远无法实际处理类型9。 Python文档没有提到zipfile不能handle other compression types

相关问题 更多 >