繁体   English   中英

如何使用 python configparser 读取缩进部分

[英]How to read indentated sections with python configparser

我尝试使用 python configparser 读取以下配置文件:

# test.conf
[section]
a = 0.3

        [subsection]
        b = 123
# main.py

import configparser
conf = configparser.ConfigParser()
conf.read("./test.conf")
a = conf['section']['a']
print(a)

Output:

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

在 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)

Output:

hello

Configparser只支持一个section,不支持subsection,如果你愿意你可以使用config obj, http://www.voidspace.org.uk/python/configobj.html

在这里检查,这可能对您有所帮助python 3 为 configparser 制作小节

pip install configobj

并且您应该在 configobj 模块中对像这样的 [[subsection]] 使用方括号

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM