如何使用list_objects_v2从S3获取1000多个对象?

2024-06-01 04:59:01 发布

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

我在s3上有超过500000个对象。我想知道每个物体的大小。我正在使用下面的python代码

import boto3

bucket = 'bucket'
prefix = 'prefix'

contents = boto3.client('s3').list_objects_v2(Bucket=bucket,  MaxKeys=1000, Prefix=prefix)["Contents"]

for c in contents:
    print(c["Size"])

但它只给了我1000个物体的大小。根据文件我们不能得到更多的1000。有什么办法能让我得到更多吗?


Tags: 对象代码importclientprefixobjectss3bucket
1条回答
网友
1楼 · 发布于 2024-06-01 04:59:01

将响应中返回的ContinuationToken用作后续调用的参数,直到响应中返回的IsTruncated值为false。

这可以分解为一个整洁的生成器函数:

def get_all_s3_objects(s3, **base_kwargs):
    continuation_token = None
    while True:
        list_kwargs = dict(MaxKeys=1000, **base_kwargs)
        if continuation_token:
            list_kwargs['ContinuationToken'] = continuation_token
        response = s3.list_objects_v2(**list_kwargs)
        yield from response.get('Contents', [])
        if not response.get('IsTruncated'):  # At the end of the list?
            break
        continuation_token = response.get('NextContinuationToken')

for file in get_all_s3_objects(boto3.client('s3'), Bucket=bucket, Prefix=prefix):
    print(file['size'])

相关问题 更多 >