-1

I'm trying to use configParser to upload .ini files. Everything is working well, until I get to a nested loop. I'm trying to find key values in each file, then in each section in that file, and print out the key-pair values.

for i in iniFiles:
    config.read(i)        
    for j in config.sections():
        if config.has_option(j, description):
            print(j + ':', config[j][description])

In the example, iniFiles is a list of strings that contain paths to each file I'm trying to look through. description is the key that I'm trying to search for. I keep looping through a few different files and for whatever reason, one of the files keeps getting repeated when I print out their key-values. Why is that?

1 Answers1

0

The config.read function doesn't work the way you probably think it does. It processes the file that you specify, but it merges the result with the already existing contents of the parser. It doesn't reinitialize the contents of the parser. So if you parse multiple files like you are doing here, each new file simply merges its contents with the existing state of the parser. You think it's reading the same file over and over again, but it's not doing that. It's simply retaining all the previous results.

The simple solution is to read all the files in at once, and then do the printing in a separate loop. Alternatively, you can create a new (and therefore empty) instance of ConfigParser for each file. I don't know which solution would work best for you.

FYI the read function can process a list of filenames in one step, which would eliminate your outer loop. Read the docs for that function.

Paul Cornelius
  • 9,245
  • 1
  • 15
  • 24