【问题标题】:Python:Retrieve chunk of a zip file and processPython:检索压缩文件的块并处理
【发布时间】:2020-08-12 02:06:45
【问题描述】:

我需要解压缩大型 zip 文件(大约 10 GB)并将其放回 S3。我的内存限制为 512 MB。

我尝试了这段代码并在line: 9 获得了MemoryError,它将整个文件内容加载到内存中,因此出现了内存错误。如何检索压缩文件的一部分,将其解压缩并上传回 S3?

import json
import boto3
import io
import zipfile

def lambda_handler(event, context):
    s3_resource = boto3.resource('s3')
    zip_obj = s3_resource.Object(bucket_name="bucket.name", key="test/big.zip")
    buffer = io.BytesIO(zip_obj.get()["Body"].read())
    z = zipfile.ZipFile(buffer)

    for filename in z.namelist():
        s3_resource.meta.client.upload_fileobj(
            z.open(filename),
            Bucket="bucket.name",
            Key=f'{"test/" + filename}'
        )

请告诉我

【问题讨论】:

    标签: python python-3.x amazon-s3 aws-lambda io


    【解决方案1】:

    我建议使用 Lambda 函数在 run instance api 的 UserData 中使用预定义脚本启动 EC2 实例,以便您可以在脚本中指定位置文件名等。在脚本中,您可以从 S3 下载 zip 并使用 linux 命令解压缩,然后递归地将整个文件夹上传到 S3。

    您可以根据您的 zip 文件大小选择 RAM/ROM,发布后您可以通过相同的脚本停止您的实例。

    【讨论】:

    • 我们需要一种无服务器方法,并且不允许使用 EC2,因此我遵循了这个:medium.com/@multiaki/…。由于我们使用 Python,您能否建议该 URL 中提到的 Python 中 NodeJS .createReadStream() 的替代方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多