我在s3上有超过500,000个对象。我正在尝试获取每个对象的大小。为此,我使用了以下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个。有没有什么办法能让我得到更多?
发布于 2020-01-20 09:51:48
内置的boto3 Paginator
类是克服list-objects-v2
1000条记录限制的最简单方法。这可以按如下方式实现
s3 = boto3.client('s3')
paginator = s3.get_paginator('list_objects_v2')
pages = paginator.paginate(Bucket='bucket', Prefix='prefix')
for page in pages:
for obj in page['Contents']:
print(obj['Size'])
发布于 2019-01-23 02:47:36
使用响应中返回的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'])
发布于 2020-01-17 23:19:47
如果不需要使用boto3.client
,可以使用boto3.resource
获取文件的完整列表:
s3r = boto3.resource('s3')
bucket = s3r.Bucket('bucket_name')
files_in_bucket = list(bucket.objects.all())
然后,要获得大小只需:
sizes = [f.size for f in files_in_bucket]
根据您的存储桶大小,这可能需要一分钟的时间。
https://stackoverflow.com/questions/54314563
复制相似问题