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每个节的唯一键
当前回答
我降落在这里想要吃掉这个…
[global]
spys = richard.sorge@cccp.gov, mata.hari@deutschland.gov
答案是用逗号分隔,然后去掉空格:
SPYS = [e.strip() for e in parser.get('global', 'spys').split(',')]
获取一个列表结果:
['richard.sorge@cccp.gov', 'mata.hari@deutschland.gov']
它可能不能准确地回答OP的问题,但可能是一些人正在寻找的简单答案。
其他回答
配置解析器只支持基本类型的序列化。对于这种需求,我会使用JSON或YAML。
我使用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]部分非常方便。
json。负载& ast.literal_eval似乎工作,但配置中的简单列表将每个字符视为字节,因此返回偶数方括号....
这意味着如果配置字段值= [1,2,3,4,5]
然后config.read (* . cfg) config['fieldValue'][0]返回[代替1
我降落在这里想要吃掉这个…
[global]
spys = richard.sorge@cccp.gov, mata.hari@deutschland.gov
答案是用逗号分隔,然后去掉空格:
SPYS = [e.strip() for e in parser.get('global', 'spys').split(',')]
获取一个列表结果:
['richard.sorge@cccp.gov', 'mata.hari@deutschland.gov']
它可能不能准确地回答OP的问题,但可能是一些人正在寻找的简单答案。
如果你想字面上传递一个列表,那么你可以使用:
ast.literal_eval()
举例配置:
[section]
option=["item1","item2","item3"]
代码是:
import ConfigParser
import ast
my_list = ast.literal_eval(config.get("section", "option"))
print(type(my_list))
print(my_list)
输出:
<type'list'>
["item1","item2","item3"]