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

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

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

[Section 3]
barList={
    item1,
    item2
}

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


当前回答

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

其他回答

很多人不知道的一件事是允许多行配置值。例如:

;test.ini
[hello]
barlist = 
    item1
    item2

config.get('hello','barlist')的值现在将是:

"\nitem1\nitem2"

你可以很容易地用splitlines方法进行分割(不要忘记过滤空项)。

如果我们看看像金字塔这样的大框架,他们正在使用这种技术:

def aslist_cronly(value):
    if isinstance(value, string_types):
        value = filter(None, [x.strip() for x in value.splitlines()])
    return list(value)

def aslist(value, flatten=True):
    """ Return a list of strings, separating the input based on newlines
    and, if flatten=True (the default), also split on spaces within
    each line."""
    values = aslist_cronly(value)
    if not flatten:
        return values
    result = []
    for value in values:
        subvalues = value.split()
        result.extend(subvalues)
    return result

我自己,我可能会扩展ConfigParser,如果这是一个常见的事情为你:

class MyConfigParser(ConfigParser):
    def getlist(self,section,option):
        value = self.get(section,option)
        return list(filter(None, (x.strip() for x in value.splitlines())))

    def getlistint(self,section,option):
        return [int(x) for x in self.getlist(section,option)]

注意,在使用这种技术时需要注意一些事情

作为项目的新行应该以空格开始(例如空格或制表符) 下面所有以空格开头的行都被认为是前一项的一部分。如果它有一个=号或者如果它以a开头;跟着空格。

你可以在配置文件中使用列表,然后在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

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

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

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

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

如果你想字面上传递一个列表,那么你可以使用:

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