[英]List AWS S3 folders with boto3
我有在 levelOne 文件夾中收集 S3 子文件夾的 boto 代碼:
import boto
s3 = boto.connect_s3()
bucket = s3.get_bucket("MyBucket")
for level2 in bucket.list(prefix="levelOne/", delimiter="/"):
print(level2.name)
請幫助發現 boto3 中的類似功能。 代碼不應遍歷所有 S3 對象,因為存儲桶有大量對象。
我認為以下內容應該是等效的:
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('MyBucket')
for object in bucket.objects.filter(Prefix="levelOne/", Delimiter="/"):
print(object.key)
如果您只是尋找文件夾列表,則使用列出對象時返回的CommonPrefixes
。 請注意,必須指定Delimiter
才能獲取CommonPrefixes
:
import boto3
s3_client = boto3.client('s3')
response = s3_client.list_objects_v2(Bucket='BUCKET-NAME', Delimiter = '/')
for prefix in response['CommonPrefixes']:
print(prefix['Prefix'][:-1])
如果您的存儲桶有大量文件夾和對象,您可以考慮使用Amazon S3 Inventory ,它可以提供每日或每周CSV文件列出所有對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.