Search code examples
pythonconfigparser

Write to lowercase 'default' section ConfigParser


I am working with an ini file where the default section is named 'default' and not 'DEFAULT'. Pythons ConfigParser seams to handle these sections ok with no problem. However, for whatever reason, they dont allow you to add a 'default' section or write to it. In the code, they have hardcoded that you can not create a section of any case-insensitive version of 'DEFAULT'.

So if I can not add the section 'default' how do I write to it? The spec says you write to 'DEFAULT' since the section always exists. However, how to I write to 'default'?

I want to stay consistent with the way the file is already written, so I want the default section to be written in lowercase and not all uppercase.

If the file doesnt exist yet, I want to add the [default] section. Writing to section 'default' gives me a ValueError: Invalid section name: default

(note: writing to default works fine when I use an already correctly formatted file)

Also, I am willing to listen to suggestions for other configuration libraries I can use. But they must not be 3rd party (I shouldn't need to pip install them)


Solution

  • Here's a workaround (setting ConfigParser.DEFAULTSECT temporarily) :

    import ConfigParser
    import sys
    
    config = ConfigParser.ConfigParser()
    config.set(ConfigParser.DEFAULTSECT, 'name', 'value')
    
    ORIG_DEFAULTSECT = ConfigParser.DEFAULTSECT # <---
    ConfigParser.DEFAULTSECT = 'default'
    try:
        config.write(sys.stdout)
    finally:
        ConfigParser.DEFAULTSECT = ORIG_DEFAULTSECT # <---
    

    Alternative: pass a StringIO with desired section name to readfp

    import ConfigParser
    import sys
    from StringIO import StringIO
    
    config = ConfigParser.ConfigParser()
    config.readfp(StringIO('[default]'))  # <----
    config.set('default', 'name', 'value')
    config.write(sys.stdout)