Search code examples
pythonconfiguration-filesconfigobj

using configobj to read a complete section one by one


I am using configobj to read a config file as below.

[default]
    PROP1 = "12345"
    PROP2 = "abcde"
[section1]
    PROP1 = "56789"
    PROP2 = ""
[section2]
    PROP1 = ""
    PROP2 = "" 

I aim to read the list of sections first and then get each section onto a dictionary. I have to replace with default values if no value is present. say section2 - PROP1 will become "12345". I have been looking at configobj to read just a section onto a dictionary object, but it looks like there is no function/method to do it. Any help?

Thanks

Umapathy


Solution

  • When you read your config file, configobj will convert it into a dictionary for you.

    >>> from configobj import ConfigObj
    
    >>> config = ConfigObj('your_config_filename')
    
    >>> config.keys()
    <<< ['default', 'section1', 'section2']
    
    >>> config['default']
    <<< {'PROP1': '12345', 'PROP2': 'abcde'}