ConfigParser生成的典型文件如下所示:
[Section]
bar=foo
[Section 2]
bar2= baz
现在,有没有一种方法来索引列表,例如:
[Section 3]
barList={
item1,
item2
}
相关问题:Python的ConfigParser每个节的唯一键
ConfigParser生成的典型文件如下所示:
[Section]
bar=foo
[Section 2]
bar2= baz
现在,有没有一种方法来索引列表,例如:
[Section 3]
barList={
item1,
item2
}
相关问题:Python的ConfigParser每个节的唯一键
当前回答
这些回答中没有提到ConfigParser()的转换器kwarg,这令人相当失望。
根据文档,您可以向ConfigParser传递一个字典,它将为解析器和节代理添加一个get方法。对于列表:
example.ini
[Germ]
germs: a,list,of,names, and,1,2, 3,numbers
解析器的例子:
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']
这是我个人最喜欢的,因为不需要子类化,我不需要依赖最终用户来完美地编写JSON或可以由ast.literal_eval解释的列表。
其他回答
这些回答中没有提到ConfigParser()的转换器kwarg,这令人相当失望。
根据文档,您可以向ConfigParser传递一个字典,它将为解析器和节代理添加一个get方法。对于列表:
example.ini
[Germ]
germs: a,list,of,names, and,1,2, 3,numbers
解析器的例子:
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']
这是我个人最喜欢的,因为不需要子类化,我不需要依赖最终用户来完美地编写JSON或可以由ast.literal_eval解释的列表。
我最近在配置文件中实现了一个列表的专用部分:
[paths]
path1 = /some/path/
path2 = /another/path/
...
使用config。Items ("paths")来获取路径项的可迭代列表,如下所示:
path_items = config.items( "paths" )
for key, path in path_items:
#do something with path
没有什么可以阻止您将列表打包到一个带分隔符的字符串中,然后在从配置中获得字符串后将其解包。如果你这样做,你的配置部分看起来像:
[Section 3]
barList=item1,item2
它并不漂亮,但对于大多数简单的列表来说,它是有用的。
我使用ConfigParser和JSON的组合:
[Foo]
fibs: [1,1,2,3,5,8,13]
只需阅读:
>>> json.loads(config.get("Foo","fibs"))
[1, 1, 2, 3, 5, 8, 13]
如果你的列表很长,你甚至可以断行(谢谢@peter-smit):
[Bar]
files_to_check = [
"/path/to/file1",
"/path/to/file2",
"/path/to/another file with space in the name"
]
当然,我可以只使用JSON,但我发现配置文件更可读,和[DEFAULT]部分非常方便。
为了进一步理解Grr的答案(我最喜欢的答案),您可以使用map函数,而不是在.ini文件中用引号括住列表项。这允许您以python方式指定列表项数据类型。
配置文件:
[section]
listKey1: 1001, 1002, 1003
listKey2: AAAA, BBBB, CCCC
代码:
cfgFile = 'config.ini'
parser = ConfigParser(converters={'list': lambda x: [i.strip() for i in x.split(',')]})
parser.read(cfgFile)
list1 = list(map(int, parser.getlist('section', 'listKey1')))
list2 = list(map(str, parser.getlist('section', 'listKey2')))
print(list1)
print(list2)
输出:
[1001, 1002, 1003]
['AAAA', 'BBBB', 'CCCC']