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

Python中使用ConfigParser时,变量传递INI文件名失效问题排查

问题:ConfigParser读取第二个配置文件失败,硬编码路径却正常

我有两个格式为[section] name=value的conf配置文件。第一个配置文件中某个值存储了第二个配置文件的名称。我可以使用ConfigParser.read()读取第一个配置文件,但当我尝试将从第一个配置文件读取到的值作为参数传入第二次ConfigParser.read()调用时,无法获取第二个配置文件的任何节。如果硬编码第二个配置文件的路径,则一切正常。

我尝试了以下代码:

from configparser import ConfigParser
config = ConfigParser()
config.read('scripts.conf')
other_config_file = config['a_section']['other_config_file']
print(other_config_file) # 验证已获取到值
config.read(other_config_file)
print(config.sections())

上述代码中,print(config.sections())仅输出第一个配置文件的节名称。

而如果使用以下代码:

from configparser import ConfigParser
config = ConfigParser()
config.read('scripts.conf')
other_config_file = config['a_section']['other_config_file']
print(other_config_file) # 验证已获取到值
config.read('/path/to/second/conf/file.conf')
print(config.sections())

此时print(config.sections())会输出两个配置文件的节名称,且变量other_config_file的内容与硬编码路径完全一致。

请问我哪里操作出错了?

更新:惭愧地承认,我之前没注意到第一个配置文件中存储的第二个配置文件路径带有双引号,首尾的引号导致路径无效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:52:08