2

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?

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.