3

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

Vignesh
  • 1,553
  • 1
  • 10
  • 25
Käseknacker
  • 221
  • 2
  • 15

2 Answers2

5

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
Delgan
  • 18,571
  • 11
  • 90
  • 141
Vignesh
  • 1,553
  • 1
  • 10
  • 25
  • Thank you so much. But why the example works in the documentation is not very intuitive. I would rather not indent lines in config files in the future instead of having to think about this bool every time. – Käseknacker Jul 27 '20 at 05:28
0

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

Vignesh
  • 1,553
  • 1
  • 10
  • 25
  • Thanks for your suggestion. I know that configparser does not support subsections. I just wanted to use the indentation to structure the config file better. According to the documentation, this should also be possible. – Käseknacker Jul 13 '20 at 04:58
  • according to documentation, it is possible, but this feature does not seem to be working, Probably we will raise a bug to configparser – Vignesh Jul 13 '20 at 05:01
  • Raised an issue for this, Hope this will be solved https://github.com/jaraco/configparser/issues/55 – Vignesh Jul 13 '20 at 05:35
  • Thanks for opening an issue. Then I read the documentation correctly and it is really a bug in the configparser package. – Käseknacker Jul 14 '20 at 07:13