如何在Python中使用Boto3库获取AWS S3中存在的存储桶列表?
问题陈述 − 使用Python中的boto3库获取AWS中所有存在的存储桶列表。
示例 − 获取存储桶名称,例如 – BUCKET_1、BUCKET2、BUCKET_3
解决此问题的方法/算法
步骤1 − 导入boto3和botocore异常以处理异常。
步骤2 − 使用Boto3库创建一个AWS会话。
步骤3 − 为S3创建一个AWS资源。
步骤4 − 使用函数buckets.all()列出存储桶名称。
步骤5 − 处理任何发生的意外异常。
步骤6 − 返回buckets_namev列表。
示例
以下代码获取S3中存在的存储桶列表:
import boto3 from botocore.exceptions import ClientError # To get list of buckets present in AWS using S3 resource def get_buckets_resource(): session = boto3.session.Session() # User can pass customized access key, secret_key and token as well s3_resource = session.resource('s3') try: buckets = list(s3_resource.buckets.all()) print("Got buckets using resource:", buckets) except ClientError: print("Couldn't get buckets.") raise else: return buckets get_buckets_resource()
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
Got buckets using resource:[s3.Bucket(name='BUCKET_1'), s3.Bucket(name='BUCKET_2'), s3.Bucket(name='BUCKET_3)………… ]
广告