使用 boto3 列出 AWS S3 文件夹

Mik*_*ine 10 python directory amazon-s3 boto boto3

我有 boto 代码,用于收集 levelOne 文件夹中的 S3 子文件夹:

import boto

s3 = boto.connect_s3()
bucket = s3.get_bucket("MyBucket")

for level2 in bucket.list(prefix="levelOne/", delimiter="/"):
    print(level2.name)
Run Code Online (Sandbox Code Playgroud)

请帮助发现 boto3 中的类似功能。该代码不应迭代所有 S3 对象,因为存储桶中的对象数量非常大。

Joh*_*ein 15

如果您只是查找文件夹列表,则CommonPrefixes在列出对象时使用 returned。请注意,Delimiter必须指定 a 才能获取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])
Run Code Online (Sandbox Code Playgroud)

如果您的存储桶具有大量文件夹和对象,您可以考虑使用Amazon S3 Inventory,它可以提供每日或每周列出所有对象的 CSV 文件。


Mar*_*cin 3

我认为以下应该是等效的:

import boto3

s3 = boto3.resource('s3') 

bucket = s3.Bucket('MyBucket')

for object in bucket.objects.filter(Prefix="levelOne/", Delimiter="/"):
    print(object.key)
Run Code Online (Sandbox Code Playgroud)

  • 根据我的经验,事实并非如此。`Delimiter` 和 `boto3.resource` 不能很好地配合。该问题在[此处](/sf/answers/3596068381/)和[此处](/sf/answers/3596075031/)进行了讨论。如果从“boto3.resource”开始是一个硬性要求,那么通过“{resource}.meta.client”获取相应的“boto3.client”似乎是最好的解决方案 (2认同)