Python上传文件至Blob存储报TypeError: string indices must be integers
问题分析
报错TypeError: string indices must be integers触发在config["source_folder"]代码行,本质原因是load_config()函数返回的config变量是字符串类型,而非代码预期的字典类型。Python中字符串仅支持整数索引(例如"test"[0]取第一个字符t),传入字符串作为索引就会抛出该错误。
排查步骤
- 验证config实际类型:在
config = load_config()代码后新增print(type(config))运行,若输出为<class 'str'>即可确认根因。 - 检查config.yaml格式:绝大多数场景是YAML文件写法不符合规范,常见问题包括:
- 整行配置被外层引号包裹,YAML解析后直接返回字符串而非键值对
- 键名缩进错误,未形成顶层键值对结构
- 文件带UTF-8 BOM头,导致键名被附加特殊字符无法匹配
- 文件内仅写了路径字符串,没有定义
source_folder键
- 验证YAML加载结果:在
load_config()函数return语句前打印加载结果,确认输出是否为包含source_folder键的字典结构。
修复方案
- 修正config.yaml为标准YAML键值对格式,参考正确示例:
source_folder: /local/path/to/your/source/dir # 可按需补充其他Blob存储相关配置 blob_connection_string: "你的存储账号连接串" target_container: "你的Blob容器名"
注意source_folder键名需顶格书写,不要给整行配置加外层包裹引号;如果文件保存为带BOM的UTF-8格式,打开文件时需指定编码为utf-8-sig。
- 给配置加载逻辑增加类型与必填项校验,提前捕获配置格式错误,修改后的
load_config函数参考:
import os import yaml from azure.storage.blob import ContainerClient def load_config(): dir_root = os.path.dirname(os.path.abspath(__file__)) config_path = os.path.join(dir_root, "config.yaml") with open(config_path, "r", encoding="utf-8") as yamlfile: config = yaml.load(yamlfile, Loader=yaml.FullLoader) # 配置合法性校验 if not isinstance(config, dict): raise RuntimeError(f"config.yaml格式错误,预期为键值对结构,实际解析结果类型为{type(config)}") if "source_folder" not in config: raise RuntimeError("config.yaml缺少必填配置项:source_folder") return config
- 替换字符串加号拼接路径的写法,改用
os.path.join适配不同操作系统的路径分隔符,修改对应代码行:
# 原写法:csvs =get_files(config["source_folder"]+"/csvs") csvs = get_files(os.path.join(config["source_folder"], "csvs"))
内容的提问来源于stack exchange,提问作者user8429520
相关产品推荐
相关产品推荐

