0

Sorry, I am a newbie in Python and trying to work on the ConfigParser module. Here is one script which is used to read multiple sections and values from a .ini file and print them as below (Current output). Now, I would like to store each of these values of url, password into variables and use each of them to run REST call using a for loop.

What changes are required to store value of each "url" and "password" into different variables?

# cat file.ini

[bugs]
url = http://localhost:1010/bugs/
username = mark
password = SECRET

[wiki]
url = http://localhost:1010/wiki/
username = chris
password = PWD

Script :-

from ConfigParser import SafeConfigParser

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

for element in parser.sections():
    print 'Section:', element
    print '  Options:', parser.options(element)
    for name, value in parser.items(element):
        print '  %s = %s' % (name, value)
    print

Current output :-

~]# python parse.py

Section: wiki
  Options: ['url', 'username', 'password']
  url = http://localhost:1010/wiki/
  username = chris
  password = PWD

Section: bugs
  Options: ['url', 'username', 'password']
  url = http://localhost:1010/bugs/
  username = mark
  password = SECRET

2 Answers 2

1
# The format is parser.get(section, tag)
bugs_url = parser.get('bugs', 'url')
bugs_username = parser.get('bugs', 'username')
bugs_password = parser.get('bugs', 'password')

wiki_url = parser.get('wiki', 'url')
wiki_username = parser.get('wiki', 'username')
wiki_password = parser.get('wiki', 'password')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Vikas.. But I would like to store each value to the same variable (for example, store value of password to a single variable "password" from both sections and also irrespective of number sections mentioned in the .ini file (i.e not specifying the name of the section explicitly).
0
from ConfigParser import SafeConfigParser

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

config_dict = {}

for element in parser.sections():
    print 'Section:', element
    config_dict[element] = {}
    print '  Options:', parser.options(element)
    for name, value in parser.items(element):
        print '  %s = %s' % (name, value)
        config_dict[element][name] = value

print config_dict

2 Comments

Sorry to ask, how do I print the value of name "password" which is repeated twice in "config_dict"
Got it.. print config_dict[element]['password']

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.