我尝试使用 python configparser 读取以下配置文件:# test.conf[section]a = 0.3 [subsection] b = 123# main.pyimport configparserconf = configparser.ConfigParser()conf.read("./test.conf")a = conf['section']['a']print(a)输出:0.3[subsection]b = 123如果我删除缩进,则 a 被正确读取。如何使用 python configparser 正确读取带有缩进的配置文件?根据文档,它应该可以工作:https ://docs.python.org/3.8/library/configparser.html#supported-ini-file-structure我使用 python 3.7.6
2 回答
慕斯王
TA贡献1864条经验 获得超2个赞
在 python 错误跟踪器中提出错误后,我找到了一种阅读指定小节的方法。添加empty_lines_in_values=False到您的代码。
错误跟踪器链接:https://bugs.python.org/issue41379
import configparser
conf = configparser.ConfigParser(empty_lines_in_values=False)
conf.read("./test.conf")
a = conf['section']['a']
print(a)
输出:
hello
德玛西亚99
TA贡献1770条经验 获得超3个赞
Configparser 只支持一个部分,没有子部分,如果你想你可以使用配置对象,http://www.voidspace.org.uk/python/configobj.html
检查这里,这可能会帮助你python 3 make subsection for configparser
pip install configobj
并且您应该在 configobj 模块中像这样对 [[subsection]] 使用双方括号
添加回答
举报
0/150
提交
取消
