Search code examples
pythonconfiginiconfigparser

Loop through config.ini file in python


I'm trying to loop through my config.ini file using values in that same config.ini file.

In my config.ini file I have the following:

[Machine_List]
List = Machine01,Machine02,Machine03
 
[SQL_Query]
Machine01 = SELECT...
Machine02 = SELECT...
Machine03 = SELECT...

In my Python code that I've tried:

Machine_List = config['Machine_List']['List']
for x in Machine_List.split(','):
   Query = config['SQL_Query'][x]

The goal is be able to add an item to the [Machine_List] List and its corresponding [SQL_Query] in the config.ini file and have python loop through each one.

After the "Query" variable is defined I use it to generate a dataframe and save that as an html file. I need a separate html file for each listed item in [Machine_List] List.

I get an error for the line Query = config['SQL_Query'][x]

The rest of my code is inside the for loop.


Solution

  • You'll want to zip the Machines list together with queries:

    Machine_List = config['Machine_List']['List']
    for machine, query in zip(Machine_List.split(','), config['SQL_Query']):
        # do something