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每个节的唯一键
当前回答
为了进一步理解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']
其他回答
我降落在这里想要吃掉这个…
[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的问题,但可能是一些人正在寻找的简单答案。
这是我用于列表的方法:
配置文件内容:
[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]
谢谢。
我更喜欢的另一种方法,就是分割这些值,例如:
#/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
对split(',')的改进可能是将逗号分隔的值视为CSV文件中的一条记录
import csv
my_list = list(csv.reader([config['Section 3']['barList']], dialect=csv.excel))[0]
您可以配置一种方言来解析任何您喜欢的CSV样式。