首页 > 解决方案 > 如何在boto3中获取过滤后的objectsCollection的大小

问题描述

我尝试了以下方法来获取s3.Bucket.objectsCollectionboto3 v1.7.37 中的 len/content_length:

import boto3    
s3 = boto3.resource('s3')
bucket = s3.Bucket('myBucket')
bucketObjects = bucket.objects.filter(Prefix='myPrefix')
if (len(bucketObjects) > 0):
     do_something()
else:
     do_something_else()

不幸的是,这给了我以下错误:

TypeError: object of type 's3.Bucket.objectsCollection' has no len()

我也试过这个bucketobjects.content_length并得到了

AttributeError: 's3.Bucket.objectsCollection' object has no attribute 'content_length'

我将不得不遍历列表并计算对象还是有更好的方法?

标签: pythonboto3

解决方案


正如 Leo K 所说bucket.objects.filter,返回没有确定长度的可迭代对象。但是您可以使用 limit 方法来限制迭代。因此,如果您想检查列表中是否找到了一项,您可以使用以下内容:

results = bucket.objects.filter(Prefix=prefix_filter) if list(results.limit(1)): do_something() else: do_something_else()


推荐阅读