Search code examples
pythonini

Python parsing ini file with global scope/properties


Sample ini file that I want to parse and change.

global_key = global_value
.include other_file.ini

[section]
key = value

Is there a way to parse and augment this with Python? I know usually ConfigParser is recommended for ini files, I didn't find any way to parse a file with global scope.


Solution

  • .ini file always requires section headers.

    In this case you can create a custom section header and use allow_no_value=True to parse with ConfigParser class. The allow_no_value=False says the parser to parse the settings without values.

    >>> string = """
    ... global_key = global_value
    ... .include other_file.ini
    ... 
    ... [section]
    ... key = value
    ... """
    >>> 
    >>> from configparser import ConfigParser
    >>> 
    >>> parser = ConfigParser(allow_no_value=True)
    >>> parser.read_string("[GLOBAL]\n" + string)
    >>> for key in parser["GLOBAL"]:
    ...     print(key)
    ... 
    global_key
    .include other_file.ini