如何修复在 aws 中列出来自 s3 存储桶的内容的关键错误?

问题描述

我有以下一段代码,它利用了 boto3 中的 list_objects_v2。我收到一个错误 => keyError : 'Contents'。我假设如果我传递的文件名不存在,它会抛出这个错误

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)

解决方法

它应该是Contents,而不是contents,假设返回了一些对象:

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