Search code examples
pythoniniconfigparser

How can I get indentation to be included in a multiline value when read from configparser in python?


I have some config file like this:

[main]
key_one   =
  hello
    this
      is
        indented

But when I read it using the configparser library in python like so:

import configparser
cfg = configparser.ConfigParser()
cfg.read("path/to/file.ini")
print(cfg["main"]["key_one"])

Prints out:

hello
this
is
indented

I've tried using tabs, more than two spaces per indent, nothing seems to work. How can I get configparser to recognize indents?


Solution

  • The parser itself will always strip leading whitespace; as far as I can tell, there is no (recommended) way to change that.

    A workaround is to use a non-whitespace character to indicate the beginning of your formatted text, then strip that after reading the file. For example,

    [main]
    key_one   =| hello
               |   this
               |     is
               |       indented
    

    Then in your script

    import configparser
    import re
    
    cfg = configparser.ConfigParser()
    cfg.read("tmp.ini")
    t = cfg["main"]["key_one"]
    t = re.sub("^\|", "", t, flags=re.MULTILINE)
    print(t)
    

    which produces

    $ python3 tmp.py
     hello
       this
         is
           indented
    

    The value starts immediately after the = (I moved your first line up, assuming you didn't really want the value to start with a newline character). The parser preserves any non-trailing whitespace after |, as the first non-whitespace character on each line. re.sub will remove the initial | from each line, leaving the desired indented multi-line string as the result.