如何在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()輸出
Got buckets using resource:[s3.Bucket(name='BUCKET_1'), s3.Bucket(name='BUCKET_2'), s3.Bucket(name='BUCKET_3)………… ]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP