frazman
frazman

Reputation: 33293

config parser python

I have a cfg file which has 10 sections..and each of the section has similar fields.

[sec1]
id:...
[sec2]
id..

...

So right now.. I am doing something like..

config_instance = ConfigParser.ConfigParser()
id1 = config_instance.get("sec1","id")
id2 = config_instance.get("sec2","id")

and so on

Is there a better more pythonic way to do this.. that it automatically reads all the sections and extracts this feature??

Thanks

Upvotes: 0

Views: 200

Answers (2)

kindall
kindall

Reputation: 184405

Make a dictionary with the sections as keys and the IDs as values.

config = ConfigParser.ConfigParser()
ids    = {}
for section in config.sections():
    if config.has_option(section, "id"):
        ids[section] = config.get(section, "id")

Upvotes: 1

mgilson
mgilson

Reputation: 310227

If all the sections have it (or if you know a list of sections that have an id field), you can do something like:

sections=config_instance.sections()
ids=[config_instance.get(sec,'id') for sec in sections]

you can then unpack them if you want, but I prefer the list:

id1,id2,... = ids

Or, you can do it as a dictionary (python 2.7+):

ids={ sec:config_instance.get(sec,'id') for sec in sections }
print ids['sec1']

It really just depends on how you want to do it.

Upvotes: 2

Related Questions