ConfigParser: use newline in INI file

Ben Finney ben+python at benfinney.id.au
Sat Oct 1 16:12:46 EDT 2016


Thorsten Kampe <thorsten at thorstenkampe.de> writes:

> ConfigParser escapes `\n` in ini values as `\\n`.

How do you demonstrate that?

Here is an example text of a config file::

    >>> import io
    >>> import textwrap

    >>> config_text = textwrap.dedent(r"""
    ...     [foo]
    ...     wibble = Lorem\nipsum.
    ...     """)
    >>> print(config_text)

    [foo]
    wibble = Lorem\nipsum.

So that text has the characters “\n” in it. (Note that I had to use the
‘r’ prefix on the string literal, in order to turn off the special
meaning of “\” and get that character literally.)

When I use a ConfigParser it reads “\n” and reproduces exactly those
characters::

    >>> import configparser

    >>> config_file = io.StringIO(config_text)
    >>> config = configparser.ConfigParser()
    >>> config.read_file(config_file)
    >>> print(config['foo']['wibble'])
    Lorem\nipsum.

So you see that the “\n” characters are preserved exactly by the
ConfigParser.

> Is there a way to signal to ConfigParser that there is a line break?

Yes, you use a line break. See the ‘configparser’ module documentation:

    Values can also span multiple lines, as long as they are indented
    deeper than the first line of the value. Depending on the parser’s
    mode, blank lines may be treated as parts of multiline values or
    ignored.

    <URL:https://docs.python.org/3/library/configparser.html#supported-ini-file-structure>

Thus::

    >>> config_text = textwrap.dedent(r"""
    ...     [foo]
    ...     wibble = Lorem
    ...         ipsum.
    ...     """)
    >>> print(config_text)

    [foo]
    wibble = Lorem
        ipsum.

    >>> config_file = io.StringIO(config_text)
    >>> config = configparser.ConfigParser()
    >>> config.read_file(config_file)
    >>> print(config['foo']['wibble'])
    Lorem
    ipsum.

-- 
 \      “Only the shallow know themselves.” —Oscar Wilde, _Phrases and |
  `\                      Philosophies for the Use of the Young_, 1894 |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list