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。

我降落在这里想要吃掉这个…

[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的问题,但可能是一些人正在寻找的简单答案。

你可以在配置文件中使用列表,然后在python中解析它

from ast import literal_eval

literal_eval("[1,2,3,4]")

import json

json.loads("[1,2,3,4]")

你也可以在你的配置文件后面使用json文件,像这样:

your config file :
[A]
json_dis = .example.jason
--------------------
your code :
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# getting items of section A
config.items('A')
# result is a list of key-values

没有什么可以阻止您将列表打包到一个带分隔符的字符串中,然后在从配置中获得字符串后将其解包。如果你这样做,你的配置部分看起来像:

[Section 3]
barList=item1,item2

它并不漂亮,但对于大多数简单的列表来说,它是有用的。

这是我用于列表的方法:

配置文件内容:

[sect]
alist = a
        b
        c

代码:

l = config.get('sect', 'alist').split('\n')

它适用于字符串

如果是数字

配置内容:

nlist = 1
        2
        3

代码:

nl = config.get('sect', 'alist').split('\n')
l = [int(nl) for x in nl]

谢谢。