有没有办法对单文件 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
这个答案 https://stackoverflow.com/a/12572031/888970演示了对 gzip 文件执行相同操作的方法。不幸的是,我无法使用相同的技术来工作zipfile
模块,因为它似乎需要随机访问正在解压缩的整个文件。
虽然我怀疑绝对所有 zip 文件都不可能,但我也怀疑几乎(?)所有现代 zip 文件都是流兼容的,并且可以进行流解压缩,例如使用https://github.com/uktrade/stream-unzip https://github.com/uktrade/stream-unzip[完全公开:最初是我写的]
其自述文件中的示例展示了如何使用 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)