kyagu
kyagu

Reputation: 183

how to fix key error in listing content from a s3 bucket in aws?

I have following piece of code, that utilizes list_objects_v2 from boto3. I get an error => keyError : 'Contents'. I am assuming if name of the file i'm passing doesn't exist , it throws this error.

import boto3
s3_R = boto3.client('s3')
s3_b = s3_R.Bucket("MyBucket")

response = s3_R.list_objects_v2(Bucket=s3_b, Prefix='myfilename')
for obj in response['contents']:
   file = obj['key']
   print(file)

Upvotes: 6

Views: 10813

Answers (1)

Marcin
Marcin

Reputation: 238169

It should be Contents, not contents, assuming some objects are returned:

response = s3_R.list_objects_v2(Bucket='MyBucket', Prefix='myfilename')

if 'Contents' in response:
   for obj in response['Contents']:
      file = obj['Key']
      print(file)
else:
   print("No objects returned")   

Upvotes: 5

Related Questions