You need to enable JavaScript to run this app. 使用boto3列举AWS S3多前缀对象时触发KeyError:'Contents'如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用boto3列举AWS S3多前缀对象时触发KeyError:'Contents'如何解决

错误原因
  • boto3的list_objects接口仅当指定S3前缀下存在匹配对象时,返回的响应字典中才会携带Contents字段。本次报错是因为env:/B前缀下没有任何匹配对象,或是前缀拼写错误、当前AWS凭证没有该前缀的读取权限,导致响应中不存在Contents字段,直接取值触发KeyError。
修复方案

优先使用AWS官方更推荐的list_objects_v2接口(老版本list_objects已处于逐步替代阶段),同时增加字段存在性判断逻辑后再遍历内容,修复后代码示例如下:

import boto3

prefix = ("env:/A", "env:/B")
s3_client = boto3.client('s3')
bucket_name = "my_bucket"

for path in prefix:
    print(path)
    resp = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=path)
    # 先判断字段存在再遍历
    if 'Contents' in resp:
        for key in resp['Contents']:
            print(key)
    else:
        print(f"前缀{path}下无匹配的S3对象")

如果需要适配前缀下对象总数超过1000的场景,可补充分页拉取逻辑,通过ContinuationToken循环拉取全部对象:

import boto3

prefix = ("env:/A", "env:/B")
s3_client = boto3.client('s3')
bucket_name = "my_bucket"

for path in prefix:
    print(path)
    continuation_token = None
    while True:
        kwargs = {"Bucket": bucket_name, "Prefix": path}
        if continuation_token:
            kwargs["ContinuationToken"] = continuation_token
        resp = s3_client.list_objects_v2(**kwargs)
        if 'Contents' in resp:
            for key in resp['Contents']:
                print(key)
        # 检查是否还有剩余对象未拉取
        if resp.get('IsTruncated'):
            continuation_token = resp['NextContinuationToken']
        else:
            break

如果确认env:/B前缀下理应存在对象,可先排查前缀拼写是否正确、当前AWS凭证是否配置了该前缀对应的s3:ListBucket权限。

内容的提问来源于stack exchange,提问作者Mihai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 20:24:03