Rayne
Rayne

Reputation: 14977

Dynamic ConfigParser (Python)

I'm wondering if there is a way to deal with dynamic config files using Python's ConfigParser. By dynamic, I mean that the config file isn't fixed in structure.

For example, I could have the config file below.

[SectionA]
FieldA1 = stringA1
FieldA2 = stringA2
FieldA3 = stringA3

[SectionB]
FieldB1 = stringB1
FieldB2 = stringB2
FieldB3 = stringB3

I could also have the config file below (an extra field-value added to Section B).

[SectionA]
FieldA1 = stringA1
FieldA2 = stringA2
FieldA3 = stringA3

[SectionB]
FieldB1 = stringB1
FieldB2 = stringB2
FieldB3 = stringB3
FieldB4 = stringB4

The same code should be used to parse both config files. So far, I've only seen examples where the fields are hard-coded, like the example given here, which would require prior knowledge of the fields in each section.

import configparser
>>> config = configparser.ConfigParser()
>>> config['DEFAULT'] = {'ServerAliveInterval': '45',
...                      'Compression': 'yes',
...                      'CompressionLevel': '9'}

Is there a way to dynamically read the fields/values in each section?

Upvotes: 2

Views: 2019

Answers (1)

user3672754
user3672754

Reputation:

from pymotw.com

from configparser import SafeConfigParser

parser = SafeConfigParser()
parser.read('config.ini')

for section_name in parser.sections():
    print ('Section:', section_name)
    print ('  Options:', parser.options(section_name))
    for name, value in parser.items(section_name):
        print(name, value)
    print()

I just made an adaptation for python3 since I see you use configparser. Enjoy!

Upvotes: 1

Related Questions