问题
I am trying to access a specific object in my s3 bucket using boto3 for deletion.
the code below is from the boto3 documentation. https://boto3.readthedocs.io/en/latest/guide/migrations3.html#accessing-a-bucket
# Boto 3
for key in bucket.objects.all():
key.delete()
great but i would much rather have a dictionary reference then iterating though objects. That isn't the greatest at scaling.
Is there a way to grab an object using its key?
edit:
I attempted this but it didnt work. Looking through the objects collection manager.
s3 = boto3.resource('s3')
bucket = s3.Bucket(AWS_UPLOAD_BUCKET)
key = bucket.objects.get(key = venueobjects3key)
回答1:
looks like this isn't possible. Here is the filtering code. its easier for me to just to iterate through the keys and find the one I want. Lame.
Filtering Some collections support extra arguments to filter the returned data set, which are passed into the underlying service operation. Use the filter() method to filter the results:
# 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))
回答2:
use the below code I think it will help you
S3 = boto3.client(
's3',
region_name = 'us-west-2',
aws_access_key_id = AWS_ACCESS_KEY_ID,
aws_secret_access_key = AWS_SECRET_ACCESS_KEY
)
#Create a file object using the bucket and object key.
fileobj = S3.get_object(
Bucket=<Bucket_Name>,
Key=<Key_Name>
)
# open the file object and read it into the variable filedata.
fileData = fileobj['Body'].read()
print(fileData)
来源:https://stackoverflow.com/questions/49470585/accessing-a-specific-key-in-a-s3-bucket-using-boto3