Search code examples
pythonconfigparser

Python ConfigParser: input section name as variable


i want to read data out of a .cnf file. It might have a lot of sections, so I want to read them out automatically. My Code Looks like this:

while numberOfSections > 0:
    check = parser.get(numberOfSections, "check")
    hostname = parser.get(numberofSections, "hostname")
    ip = parser.get(numberofSections, "IP")
    port = parser.get(numberofSections, "port")
    request = parser.get(numberofSections, "request")

Now unfortunately, it just says "No section: 5". My numberofSections variable in this example is 5, so that's that. The sections are named like this:

[1]
check = ''
hostname = ''
IP = ''
port = ''
request = ''

[2]
check = ''
hostname = ''
IP = ''
port = ''
request = ''

[3]
check = ''
hostname = ''
IP = ''
port = ''
request = ''

...

So, any ideas? I'm new to python, so please explain it slowly.


Solution

  • Exception No section: 5 was returned because you are using while loop with always true argument.

    You should use for loop, something like:

    for section in config.sections():
        check = parser.get(section, "check")
        hostname = parser.get(section, "hostname")
        ip = parser.get(section, "IP")
        port = parser.get(section, "port")
        request = parser.get(section, "request")