python - How to ConfigParse a file keeping multiple values for identical keys? -
i need able use configparser read multiple values same key. example config file:
[test] foo = value1 foo = value2 xxx = yyy with 'standard' use of configparser there 1 key foo value value2. need parser read in both values.
following entry on duplicate key have created following example code:
from collections import ordereddict configparser import rawconfigparser class orderedmultisetdict(ordereddict): def __setitem__(self, key, value): try: item = self.__getitem__(key) except keyerror: super(orderedmultisetdict, self).__setitem__(key, value) return print "item: ", item, value if isinstance(value, list): item.extend(value) else: item.append(value) super(orderedmultisetdict, self).__setitem__(key, item) config = rawconfigparser(dict_type = ordereddict) config.read(["test.cfg"]) print config.get("test", "foo") print config.get("test", "xxx") config2 = rawconfigparser(dict_type = orderedmultisetdict) config2.read(["test.cfg"]) print config2.get("test", "foo") print config.get("test", "xxx") the first part (with config) reads in config file 'usual', leaving value2 value foo (overwriting/deleting other value) , following, expected output:
value2 yyy the second part (config2) uses approach append multiple values list, output instead
['value1', 'value2', 'value1\nvalue2'] ['yyy', 'yyy'] how rid of repetitive values? expecting output follows:
['value1', 'value2'] yyy or
['value1', 'value2'] ['yyy'] (i don't mind if every value in list...). suggestions welcome.
after small modification, able achieve want:
class multiordereddict(ordereddict): def __setitem__(self, key, value): if isinstance(value, list) , key in self: self[key].extend(value) else: super(ordereddict, self).__setitem__(key, value) config = configparser.rawconfigparser(dict_type=multiordereddict) config.read(['a.txt']) print config.get("test", "foo") print config.get("test", "xxx") outputs:
['value1', 'value2'] ['yyy']
Comments
Post a Comment