Python S3 下载 zip 文件

标签 python amazon-s3 zip

我已将 zip 文件上传到 S3。我想下载它们进行处理。我不需要永久存储它们,但我需要临时处理它们。我该怎么做呢?

最佳答案

因为工作软件 > 全面的文档:

博托2

import zipfile
import boto
import io

# Connect to s3
# This will need your s3 credentials to be set up 
# with `aws configure` using the aws CLI.
#
# See: https://aws.amazon.com/cli/
conn = boto.s3.connect_s3()

# get hold of the bucket
bucket = conn.get_bucket("my_bucket_name")

# Get hold of a given file
key = boto.s3.key.Key(bucket)
key.key = "my_s3_object_key"

# Create an in-memory bytes IO buffer
with io.BytesIO() as b:

    # Read the file into it
    key.get_file(b)

    # Reset the file pointer to the beginning
    b.seek(0)

    # Read the file as a zipfile and process the members
    with zipfile.ZipFile(b, mode='r') as zipf:
        for subfile in zipf.namelist():
            do_stuff_with_subfile()

Boto3

import zipfile
import boto3
import io

# this is just to demo. real use should use the config 
# environment variables or config file.
#
# See: http://boto3.readthedocs.org/en/latest/guide/configuration.html

session = boto3.session.Session(
    aws_access_key_id="ACCESSKEY", 
    aws_secret_access_key="SECRETKEY"
)

s3 = session.resource("s3")
bucket = s3.Bucket('stackoverflow-brice-test')
obj = bucket.Object('smsspamcollection.zip')

with io.BytesIO(obj.get()["Body"].read()) as tf:

    # rewind the file
    tf.seek(0)

    # Read the file as a zipfile and process the members
    with zipfile.ZipFile(tf, mode='r') as zipf:
        for subfile in zipf.namelist():
            print(subfile)

使用 Python3 在 MacOSX 上测试。

关于Python S3 下载 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23376816/

相关文章:

directory - 谷歌云存储上的 gsutil zip 目录

python - 如何根据Python中其他列的条件将字符串列拆分为另一列?

python - 是否可以获取 Cassandra 组合键的所有值?

amazon-web-services - terraform - 如何为 lambda 添加 s3 对象创建触发器

ios - AWS S3 请求使用从 TVM 客户端获取的凭据失败

c++ - wxImage 通过流压缩文件。可能的?

java - 一次从 zip 文件中读取一行 CSV

python - 列出 __iadd__、+= 和返回值

python - 计算 ndarray 中的唯一切片数

java - 在 Jenkins 上为多个环境构建工件并将它们上传到 S3