Using ConfigParser in Python with INI name in a variable

30 Views Asked by At

I have two 'conf' files with content in '[section] name=value' format.

The first conf file has a value that contains the name of a second conf file. I can use ConfigParser.read() to read the first conf file, but when I try to use one of the values read from the first conf file as an input to a second call to ConfigParser.read() I don't get any of the sections from the second conf file returned.

If I hard-code the path to the second config file then everything works as I expect.

So far I have tried this:

    from configparser import ConfigParser
    config = ConfigParser()
    config.read('scripts.conf')
    other_config_file = config['a_section']['other_config_file']
    print(other_config_file) # just to prove I have a valid value
    config.read(other_config_file)
    print(config.sections())

The print(config.sections() above prints JUST the section names from the first config file.

If I do this...

    from configparser import ConfigParser
    config = ConfigParser()
    config.read('scripts.conf')
    other_config_file = config['a_section']['other_config_file']
    print(other_config_file) # just to prove I have a valid value
    config.read('/path/to/second/conf/file.conf')
    print(config.sections())

...the print(config.sections()) prints the section names from BOTH files. In the second code snippet above, the variable other_config_file has the same content as the hard-coded path.

Does anyone have any ideas what I'm doing wrong?

UPDATE: Rather ashamed to admit that I had neglected to notice that the path to the second config file had been quoted in the first config file. The presence of the leading and trailing double quotes invalidated the path.

0

There are 0 best solutions below