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

后端 未结 5 2036
日久生厌
日久生厌 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:36

    in python 3.8 you need to also add strict=False:

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

提交回复
热议问题