如何按目录隔离S3存储桶中的文件?

How to isolate files in S3 bucket by directory?

我有一个 s3 存储桶 mybucket 包含以下目录结构中的三个文件

a/b/c/d/some_file.txt
a/b/d/d/some_file2.txt
x/y/z/yet_another_file.txt

我可以使用以下命令列出所有文件:

import boto3

# Extract the files from the s3 bucket
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
bucket_files = [x.key for x in bucket.objects.all()]

尽管这会生成 s3 存储桶中的所有文件,例如:

a/b/c/d/some_file.txt
a/b/d/d/some_file2.txt
x/y/z/yet_another_file.txt

如何只列出 a 中的文件?例如

a/b/c/d/some_file.txt
a/b/d/d/some_file2.txt

filterPrefix 一起使用:

import boto3

# Extract the files from the s3 bucket
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
bucket_files = [x.key for x in bucket.objects.filter(Prefix='a/')]

另一个选项:

import boto3
s3 = boto3.client('s3')
resp = s3.list_objects_v2(Bucket='mybucket', Prefix='a')