ConfigParser生成的典型文件如下所示:

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

现在,有没有一种方法来索引列表,例如:

[Section 3]
barList={
    item1,
    item2
}

相关问题:Python的ConfigParser每个节的唯一键


当前回答

json。负载& ast.literal_eval似乎工作,但配置中的简单列表将每个字符视为字节,因此返回偶数方括号....

这意味着如果配置字段值= [1,2,3,4,5]

然后config.read (* . cfg) config['fieldValue'][0]返回[代替1

其他回答

在我的项目中,我用带键没有值的section完成了类似的任务:

import configparser

# allow_no_value param says that no value keys are ok
config = configparser.ConfigParser(allow_no_value=True)

# overwrite optionxform method for overriding default behaviour (I didn't want lowercased keys)
config.optionxform = lambda optionstr: optionstr

config.read('./app.config')

features = list(config['FEATURES'].keys())

print(features)

输出:

['BIOtag', 'TextPosition', 'IsNoun', 'IsNomn']

app.config:

[FEATURES]
BIOtag
TextPosition
IsNoun
IsNomn

我更喜欢的另一种方法,就是分割这些值,例如:

#/path/to/config.cfg
[Numbers]
first_row = 1,2,4,8,12,24,36,48

可以像这样加载到字符串或整数列表中,如下所示:

import configparser

config = configparser.ConfigParser()
config.read('/path/to/config.cfg')

# Load into a list of strings
first_row_strings = config.get('Numbers', 'first_row').split(',')

# Load into a list of integers
first_row_integers = [int(x) for x in config.get('Numbers', 'first_row').split(',')]

这种方法可以避免将值包装在括号中以JSON形式加载。

我最近在配置文件中实现了一个列表的专用部分:

[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

这是我用于列表的方法:

配置文件内容:

[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]

谢谢。

json。负载& ast.literal_eval似乎工作,但配置中的简单列表将每个字符视为字节,因此返回偶数方括号....

这意味着如果配置字段值= [1,2,3,4,5]

然后config.read (* . cfg) config['fieldValue'][0]返回[代替1