python - 如何在boto3中获取过滤后的objectsCollection的大小
问题描述
我尝试了以下方法来获取s3.Bucket.objectsCollection
boto3 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'
我将不得不遍历列表并计算对象还是有更好的方法?
解决方案
正如 Leo K 所说bucket.objects.filter
,返回没有确定长度的可迭代对象。但是您可以使用 limit 方法来限制迭代。因此,如果您想检查列表中是否找到了一项,您可以使用以下内容:
results = bucket.objects.filter(Prefix=prefix_filter)
if list(results.limit(1)):
do_something()
else:
do_something_else()
推荐阅读
- kubernetes - Istio-proxy 不会通过 global.proxy.includeIPRanges 配置拦截传出流量
- namespaces - “http://”或“mailto:”是否被视为语义语言(如 RDF)中的命名空间?
- reactjs - 道具更改后反应组件不会重新渲染
- naming-conventions - UI 和 DB 中相同概念的不同名称的命名约定
- windows - Qt:如何避免 Windows 软键盘覆盖输入字段?
- javascript - Node.js azure web 应用程序无法访问我的路线
- apache-camel - 如何在内容丰富()中使用骆驼的 Exchange setProperty?
- javascript - Javascript如何将元素附加到具有特定类的div
- c# - 使用 SQLiteParameter 设置默认值
- python - 为什么我的 python 字数统计程序不起作用?