使用 boto3 访问 s3 存储桶中的特定密钥

6 amazon-s3 boto3

我正在尝试使用 boto3 访问 s3 存储桶中的特定对象进行删除。

下面的代码来自 boto3 文档。 https://boto3.readthedocs.io/en/latest/guide/migrations3.html#accessing-a-bucket

# Boto 3
for key in bucket.objects.all():
    key.delete()
Run Code Online (Sandbox Code Playgroud)

很棒,但我更愿意有一个字典参考,然后迭代对象。这并不是最大的扩展性。

有没有办法使用它的键来抓取一个对象?

编辑:

我尝试了这个,但没有成功。查看对象集合管理器。

s3 = boto3.resource('s3')
bucket = s3.Bucket(AWS_UPLOAD_BUCKET)
key = bucket.objects.get(key = venueobjects3key)
Run Code Online (Sandbox Code Playgroud)

小智 0

看起来这是不可能的。这是过滤代码。对我来说,迭代键并找到我想要的键更容易。瘸。

过滤 某些集合支持额外的参数来过滤返回的数据集,这些数据集将传递到底层服务操作中。使用filter()方法过滤结果:

# S3 list all keys with the prefix 'photos/'
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
    for obj in bucket.objects.filter(Prefix='photos/'):
        print('{0}:{1}'.format(bucket.name, obj.key))
Run Code Online (Sandbox Code Playgroud)