如何使用 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)

输出:

0.3

[subsection]
b = 123

如果我删除缩进,a 就会被正确读取。

如何使用 python configparser 正确读取带有缩进的配置文件?

根据文档,它应该可以工作:
https://docs.python.org/3.8/library/configparser.html#supported-ini-file-structure

我用的是python3.7.6

Configparser只支持一个section,不支持sub sections,如果需要可以使用config obj,http://www.voidspace.org.uk/python/configobj.html

检查这里,这可能对你有帮助

pip install configobj

你应该在 configobj 模块中像这样对 [[subsection]] 使用双方括号

在 python 错误跟踪器中提出错误后,我找到了一种阅读指定小节的方法。 将 empty_lines_in_values=False 添加到您的代码中。

错误跟踪器 link 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