You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将配置文件的整个section解析为Python字典?

把ConfigParser配置文件的指定Section转为字典批量处理

我用Python的ConfigParser生成了包含多个section的ini配置文件,现在需要解析其中某个section的所有配置项,不想手动逐个调用get()方法,希望直接将整个section转为字典,甚至批量生成对应变量(比如通过exec),同时保留配置文件统一管理多section的优势。

配置文件生成代码

from configparser import ConfigParser
config = ConfigParser()

config['section'] = {'a': 'value1',
                   'b': 'value2',
                   'c': 'value3',
                   'd': 'value4',
                   'e': 'value1'}

with open('/path/to/propFile_autolaunch.ini', 'w') as f:
    config.write(f)

当前手动读取方式

from configparser import ConfigParser
propFile = '/path/to/propFile_autolaunch.ini'
propParser = ConfigParser()
propParser.read(propFile)

# 手动逐个读取配置项
var_a = propParser.get('section', 'a')
var_b = propParser.get('section', 'b')
# ... 重复此操作处理所有配置项

直接将Section转为字典

ConfigParser的section对象本身是类字典结构,直接用dict()转换就能得到该section的完整键值对字典:

from configparser import ConfigParser
propFile = '/path/to/propFile_autolaunch.ini'
propParser = ConfigParser()
propParser.read(propFile)

# 将目标section转为字典
d_params = dict(propParser['section'])

得到字典后,可直接遍历或访问配置项:

# 批量处理所有配置项
for key, val in d_params.items():
    print(f"{key}: {val}")

批量生成变量的安全替代方案

不推荐使用exec(key + '=val'),这种方式存在安全风险(若配置文件被篡改可能执行恶意代码),且不利于代码维护。如果确实需要将配置项转为当前命名空间的变量,可用globals()或locals()更新:

# 将字典键值对注入全局命名空间(谨慎使用)
globals().update(d_params)
# 之后可直接访问变量
print(a)  # 输出: value1
print(b)  # 输出: value2

注意:globals().update()会污染全局命名空间,优先推荐直接通过d_params[key]访问配置项,更安全清晰。

完整示例代码

from configparser import ConfigParser

propFile = '/path/to/propFile_autolaunch.ini'
propParser = ConfigParser()
propParser.read(propFile)

# 获取目标section的字典
section_dict = dict(propParser['section'])

# 推荐:直接通过字典访问配置
print(section_dict['a'])

# 可选:注入到命名空间(谨慎使用)
globals().update(section_dict)
print(c)  # 输出: value3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:55:16