How to read indentated sections with python configparser

Viewed 1221

I try to read the following config file with 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

If I remove the indents, a is read correctly.

How can I read a config file with indents correctly with python configparser?

According to the docs, it should work:
https://docs.python.org/3.8/library/configparser.html#supported-ini-file-structure

I use python 3.7.6

2 Answers

After raising a bug in python bug tracker, iI have found a way to read the indended subsections. Add empty_lines_in_values=False to your code.

Bug tracker 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)

Output:

hello
Related