Search code examples
pythonpython-3.xconfigparser

How to preserve keys with capital letters read from a config-file with configparser?


When reading out a config file with python's configparser package, all key names are lowercase strings. Does anybody know how to read the strings preserving capital and uppercase words?

For example:

$cat config.cfg 
[DEFAULT]
Key_1 = SomeWord
KEY_2 = Another Word

$ python3
>>> from configparser import ConfigParser
>>> cf = ConfigParser()
>>> cf.read('./config.cfg')
['./config.cfg']
>>> print(cf.defaults())
OrderedDict([('key_1', 'SomeWord'), ('key_2', 'Another Word')])

Thanks for any help!


Solution

  • Yes, all keys are automatically transformed to lowercase during read/write operations. This is mentioned in the last sentence of the Quick Start section of the configparser docs.

    To not have this effect you can set your parsers' optionxform (a callable) to simply return the option rather than transform it to lowercase:

    >>> from configparser import ConfigParser
    >>> c = ConfigParser()
    >>> c.optionxform = lambda option: option
    >>> c.read('./config.cfg')
    ['./config.cfg']
    

    Now keys are preserved as they were defined:

    >>> c.defaults()
    OrderedDict([('Key_1', 'SomeWord'), ('KEY_2', 'Another Word')])
    

    Of course you can customize this to your liking, if, for example, you wanted all keys to uppercase you could set that in optionxform:

    >>> cf = ConfigParser()
    >>> cf.optionxform = lambda option: option.upper()
    >>> cf.read('./config.cfg')
    ['./config.cfg']
    >>> cf.defaults()
    OrderedDict([('KEY_1', 'SomeWord'), ('KEY_2', 'Another Word')])