How to ConfigParse a file keeping multiple values for identical keys?

后端 未结 5 2052
日久生厌
日久生厌 2020-12-08 17:17

I need to be able to use the ConfigParser to read multiple values for the same key. Example config file:

[test]
foo = value1
foo = value2
xxx =          


        
5条回答
  •  孤街浪徒
    2020-12-08 17:31

    After a small modification, I was able to achieve what you want:

    class MultiOrderedDict(OrderedDict):
        def __setitem__(self, key, value):
            if isinstance(value, list) and key in self:
                self[key].extend(value)
            else:
                super(MultiOrderedDict, self).__setitem__(key, value)
                # super().__setitem__(key, value) in Python 3
    
    config = ConfigParser.RawConfigParser(dict_type=MultiOrderedDict)
    config.read(['a.txt'])
    print config.get("test",  "foo")
    print config.get("test",  "xxx")
    

    Outputs:

    ['value1', 'value2']
    ['yyy']
    

提交回复
热议问题