Lists in ConfigParser

后端 未结 15 2001
清酒与你
清酒与你 2020-11-27 09:38

The typical ConfigParser generated file looks like:

[Section]
bar=foo
[Section 2]
bar2= baz

Now, is there a way to index lists like, for in

15条回答
  •  一生所求
    2020-11-27 10:20

    No mention of the converters kwarg for ConfigParser() in any of these answers was rather disappointing.

    According to the documentation you can pass a dictionary to ConfigParser that will add a get method for both the parser and section proxies. So for a list:

    example.ini

    [Germ]
    germs: a,list,of,names, and,1,2, 3,numbers
    

    Parser example:

    cp = ConfigParser(converters={'list': lambda x: [i.strip() for i in x.split(',')]})
    cp.read('example.ini')
    cp.getlist('Germ', 'germs')
    ['a', 'list', 'of', 'names', 'and', '1', '2', '3', 'numbers']
    cp['Germ'].getlist('germs')
    ['a', 'list', 'of', 'names', 'and', '1', '2', '3', 'numbers']
    

    This is my personal favorite as no subclassing is necessary and I don't have to rely on an end user to perfectly write JSON or a list that can be interpreted by ast.literal_eval.

提交回复
热议问题