0

I need pointers to parse an INI file using python 2.7 ConfigParser that looks like the following:

[google]
www.google.com domain_name=google location=external 

[yahoo]
www.yahoo.com domain_name=yahoo location=external

This is what I have tried to do:

Config = ConfigParser.ConfigParser()
try:
    Config.read("test.ini")
except Exception:
    pass

options = Config.options('google')
for option in options:
    print("Option is %s" % option)
    print("Value for %s is %s" % (option, Config.get('google', option)))

And this is what the output is:

Option is www.google.com domain_name
Value for www.google.com domain_name is google location=external

I want to be able to parse www.google.com, and remaining key=value pairs(domain_name=google; location=external) in the same line for every section into a dictionary. Any pointers for this appreciated.

new_c_user
  • 123
  • 2
  • 12
  • Seems the problem is that ConfigParser has different assumptions about the possible structure of the file. May I ask what is your goal? Maybe you could use Ansible directly? – Thomas Hirsch Feb 23 '19 at 10:39

1 Answers1

0

What I think you are asking is a way to loop through the different sections and add all the option values into a dictionary.

if you are not stuck on the layout you could do something like this

[google]
option=url=www.google.com,domain_name=google,location=external

[yahoo]
option=url=www.yahoo.com,domain_name=yahoo,location=external
import configparser

Config = configparser.ConfigParser()
try:
    Config.read("test.ini")
except Exception:
    pass

for section in Config.sections():
    for option in Config.options(section):
        values = Config.get(section, option)
        dict_values = dict(x.split('=') for x in values.split(','))

You could also do a dictionary of a dictionary, but your option will need to be unique.

dict_sections = {}
for section in Config.sections():
    for option in Config.options(section):
        values = Config.get(section, option)
        dict_values = dict(x.split('=') for x in values.split(','))
        dict_sections[option] = dict_values

Another formatting option:

[web_sites]
yahoo=url=www.yahoo.com,domain_name=yahoo,location=external
google=url=www.google.com,domain_name=google,location=external

Hope this helps!

L0ngSh0t
  • 361
  • 2
  • 9