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

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

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

我过去也遇到过同样的问题。如果需要更复杂的列表,可以考虑通过继承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 ]

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

[Section 3]
barList=item1,item2

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

我使用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]部分非常方便。

在我的项目中,我用带键没有值的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