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

Viewed 3042

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)
1 Answers

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")   
Related