mat*_*ieu 5 python configparser
我想使用python ConfigParser模块读取配置文件:
[asection]
option_a = first_value
option_a = second_value
Run Code Online (Sandbox Code Playgroud)
我希望能够获得为选项“ option_a”指定的值的列表。我尝试了以下显而易见的方法:
test = """[asection]
option_a = first_value
option_a = second_value
"""
import ConfigParser, StringIO
f = StringIO.StringIO(test)
parser = ConfigParser.ConfigParser()
parser.readfp(f)
print parser.items()
Run Code Online (Sandbox Code Playgroud)
哪个输出:
[('option_a', 'second_value')]
Run Code Online (Sandbox Code Playgroud)
当我希望:
[('option_a', 'first_value'), ('option_a', 'second_value')]
Run Code Online (Sandbox Code Playgroud)
或者,甚至更好:
[('option_a', ['first_value', 'second_value'])]
Run Code Online (Sandbox Code Playgroud)
有没有办法用ConfigParser做到这一点?另一个主意?
似乎可以读取同一键的多个选项,这可能会有所帮助: How to ConfigParse a file saving multiple values forame key?
这是此链接的最终代码(我在 python 3.8 上测试):
from collections import OrderedDict
from configparser import ConfigParser
class ConfigParserMultiValues(OrderedDict):
def __setitem__(self, key, value):
if key in self and isinstance(value, list):
self[key].extend(value)
else:
super().__setitem__(key, value)
@staticmethod
def getlist(value):
return value.splitlines()
config = ConfigParser(strict=False, empty_lines_in_values=False, dict_type=ConfigParserMultiValues, converters={"list": ConfigParserMultiValues.getlist})
config.read(["test.ini"])
values = config.getlist("test", "foo")
print(values)
Run Code Online (Sandbox Code Playgroud)
对于包含以下内容的 test.ini 文件:
[test]
foo = value1
foo = value2
xxx = yyy
Run Code Online (Sandbox Code Playgroud)
输出是:
['value1', 'value2']
Run Code Online (Sandbox Code Playgroud)