Skip to main content
 首页 » 编程设计

python之python中zip文件的流式解压缩

2025年05月04日10Free-Thinker

有没有办法对单文件 zip 存档进行流式解压缩?

我目前在 s3 中有任意大的压缩文件(每个文件一个文件)。我希望能够通过遍历文件来处理文件,而不必实际将文件下载到磁盘或内存中。

一个简单的例子:

import boto 
 
def count_newlines(bucket_name, key_name): 
    conn = boto.connect_s3() 
    b = conn.get_bucket(bucket_name) 
    # key is a .zip file 
    key = b.get_key(key_name) 
 
    count = 0 
    for chunk in key: 
        # How should decompress happen? 
        count += decompress(chunk).count('\n') 
 
    return count 

This answer演示了对 gzip 文件执行相同操作的方法。不幸的是,我无法使用 zipfile 模块获得相同的技术,因为它似乎需要随机访问正在解压缩的整个文件。

请您参考如下方法:

虽然我怀疑不可能对所有 zip 文件都适用,但我也怀疑几乎(?)所有现代 zip 文件都是流式兼容的,并且可以进行流式解压缩,例如使用 https://github.com/uktrade/stream-unzip [完全披露:最初由我撰写]

其 README 中的示例显示了如何使用 httpx 对任意 http 请求执行此操作

from stream_unzip import stream_unzip 
import httpx 
 
def zipped_chunks(): 
    # Any iterable that yields a zip file 
    with httpx.stream('GET', 'https://www.example.com/my.zip') as r: 
        yield from r.iter_bytes(chunk_size=65536) 
 
for file_name, file_size, unzipped_chunks in stream_unzip(zipped_chunks()): 
    for chunk in unzipped_chunks: 
        print(chunk) 

但我认为它可以适用于 boto3 以从 S3 流式传输解压缩/解压缩(未经测试):

from stream_unzip import stream_unzip 
import boto3 
 
def zipped_chunks(): 
    yield from boto3.client('s3', region_name='us-east-1').get_object( 
        Bucket='my-bucket-name', 
        Key='the/key/of/the.zip' 
    )['Body'].iter_chunks() 
 
for file_name, file_size, unzipped_chunks in stream_unzip(zipped_chunks()): 
    for chunk in unzipped_chunks: 
        print(chunk)