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']
其他回答
对split(',')的改进可能是将逗号分隔的值视为CSV文件中的一条记录
import csv
my_list = list(csv.reader([config['Section 3']['barList']], dialect=csv.excel))[0]
您可以配置一种方言来解析任何您喜欢的CSV样式。
我过去也遇到过同样的问题。如果需要更复杂的列表,可以考虑通过继承ConfigParser来创建自己的解析器。然后你会用它覆盖get方法:
def get(self, section, option):
""" Get a parameter
if the returning value is a list, convert string value to a python list"""
value = SafeConfigParser.get(self, section, option)
if (value[0] == "[") and (value[-1] == "]"):
return eval(value)
else:
return value
有了这个解决方案,您还可以在配置文件中定义字典。
但是要小心!这并不安全:这意味着任何人都可以通过您的配置文件运行代码。如果安全性在你的项目中不是问题,我会考虑直接使用python类作为配置文件。下面的文件比ConfigParser文件更强大、更可消耗:
class Section
bar = foo
class Section2
bar2 = baz
class Section3
barList=[ item1, item2 ]
我更喜欢的另一种方法,就是分割这些值,例如:
#/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
如果你想字面上传递一个列表,那么你可以使用:
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"]