如何在 Python 中使用 Boto3 库来获取 AWS S3 中存在的存储桶列表?
问题陈述-使用Python中的boto3库获取AWS中存在的所有存储桶的列表。
示例-获取桶的名称,如–BUCKET_1、BUCKET2、BUCKET_3
解决这个问题的方法/算法
步骤1-导入boto3和botocore异常以处理异常。
步骤2-使用Boto3库创建AWS会话。
第3步-为S3创建AWS资源
Step4-使用该函数列出存储桶名称。buckets.all()
第5步-处理任何不需要的异常(如果发生)
第6步-返回buckets_namev列表
例子
以下代码获取S3中存在的存储桶列表-
import boto3 frombotocore.exceptionsimport ClientError #使用S3资源获取AWS中存在的存储桶列表 def get_buckets_resource(): session = boto3.session.Session() #用户也可以传递自定义的访问密钥、secret_key和令牌 s3_resource = session.resource('s3') try: buckets = list(s3_resource.buckets.all()) print("使用资源获得存储桶:", buckets) except ClientError: print("Couldn't get buckets.") raise else: return buckets get_buckets_resource()
输出
使用资源获得存储桶:[s3.Bucket(name='BUCKET_1'), s3.Bucket(name='BUCKET_2'), s3.Bucket(name='BUCKET_3)………… ]