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

标签 amazon-web-services amazon-s3 boto3

我有以下一段代码,它利用了 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")   

关于amazon-web-services - 如何修复在 aws 中列出来自 s3 存储桶的内容的关键错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68371889/

相关文章:

aws-lambda - 使用 AWS Glue 调用 Lambda 函数

amazon-web-services - Amazon S3 限制对移动应用程序上特定 HTTP 引荐来源网址的访问

amazon-web-services - 可以为多个维度的指标定义 CloudWatch 警报吗

amazon-web-services - AWS Fargate 503 服务暂时不可用

amazon-web-services - 单个 Docker 镜像从 VSTS 构建/发布定义推送到 AWS 弹性容器注册表 (ECR)

php - 无法将文件上传到主存储桶的子文件夹

python - 使用 boto3 通过与特定文件名匹配的 S3 对象分页

python - 如何使用 boto3 在 Python 中获取 S3 目录作为 os.path?

amazon-web-services - 从存储桶策略中排除一个 Amazon S3 对象