Boto3:使用boto3.resource('s3')列出所有S3存储桶

Eyt*_*tan 5 amazon-s3 amazon-web-services python-3.x boto3

是否可以使用boto3资源列出所有S3存储桶,即boto3.resource('s3')

我知道可以使用低级服务客户端来这样做:

import boto3
boto3.client('s3').list_buckets()
Run Code Online (Sandbox Code Playgroud)

但是,在理想的世界中,我们可以在更高级别的资源上运行。有没有一种方法可以使我们做到?如果没有,为什么?

hel*_*loV 5

您可以使用s3.buckets.all()

s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
  print(bucket.name)
Run Code Online (Sandbox Code Playgroud)

使用列表理解:

s3 = boto3.resource('s3')
buckets = [bucket.name for bucket in s3.buckets.all()]
print(buckets)
Run Code Online (Sandbox Code Playgroud)