Reputation: 3174
I would like to read a configuration file with the python ConfigParser module:
[asection]
option_a = first_value
option_a = second_value
And I want to be able to get the list of values specified for option 'option_a'. I tried the obvious following:
test = """[asection]
option_a = first_value
option_a = second_value
"""
import ConfigParser, StringIO
f = StringIO.StringIO(test)
parser = ConfigParser.ConfigParser()
parser.readfp(f)
print parser.items()
Which outputs:
[('option_a', 'second_value')]
While I was hoping for:
[('option_a', 'first_value'), ('option_a', 'second_value')]
Or, even better:
[('option_a', ['first_value', 'second_value'])]
Is there a way to do this with ConfigParser ? Another idea ?
Upvotes: 6
Views: 2156
Reputation: 36
It seems that it is possible to read multiple options for the same key, this may help: How to ConfigParse a file keeping multiple values for identical keys?
Here is a final code from this link (I tested on python 3.8):
from collections import OrderedDict
from configparser import ConfigParser
class ConfigParserMultiValues(OrderedDict):
def __setitem__(self, key, value):
if key in self and isinstance(value, list):
self[key].extend(value)
else:
super().__setitem__(key, value)
@staticmethod
def getlist(value):
return value.splitlines()
config = ConfigParser(strict=False, empty_lines_in_values=False, dict_type=ConfigParserMultiValues, converters={"list": ConfigParserMultiValues.getlist})
config.read(["test.ini"])
values = config.getlist("test", "foo")
print(values)
For test.ini file with content:
[test]
foo = value1
foo = value2
xxx = yyy
The output is:
['value1', 'value2']
Upvotes: 2