Käseknacker
Käseknacker

Reputation: 271

How to read indentated sections with python configparser

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

Upvotes: 3

Views: 2337

Answers (2)

Vignesh
Vignesh

Reputation: 1623

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

Upvotes: 5

Vignesh
Vignesh

Reputation: 1623

Configparser supports only one section and no sub sections, if you want you can use config obj, http://www.voidspace.org.uk/python/configobj.html

check here, this might help you python 3 make subsection for configparser

pip install configobj

and you should use double square bracket for a [[subsection]] like this in configobj module

Upvotes: 0

Related Questions