0

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

1
  • 1
    Assuming Python 2.X, unless you require backwards compatibility with existing code you should probably be using ConfigParser.SafeConfigParser. Commented Jul 13, 2012 at 0:38

2 Answers 2

2

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.

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

Comments

1

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.