[英]Read all the content from .config file & insert into a dictionary with python
I there any way to insert all the content of config file & insert into a dictionary. 我有任何方法可以插入配置文件的所有内容并插入字典中。
Config file is a nest dictionary: 配置文件是一个嵌套字典:
[A]
x:1
y:2
z:3
[B]
a:4
b:5
c:6
Is there any way to to get the details as {A:{x:1,y:2,z:3}, B:{a:4,b:5,c:6}}
. 有没有办法以
{A:{x:1,y:2,z:3}, B:{a:4,b:5,c:6}}
。
Above is a sample .Can we do this with generic(not specific to this config file) 上面是一个示例。我们可以使用泛型(不特定于此配置文件)执行此操作吗?
Use ConfigParser
: 使用
ConfigParser
:
>>> s = """
[A]
x:1
y:2
z:3
[B]
a:4
b:5
c:6"""
>>> from ConfigParser import ConfigParser
>>> from StringIO import StringIO
>>> parser = ConfigParser()
>>> parser.readfp(StringIO(s))
>>> {section: {key: value
for key, value in parser.items(section)}
for section in parser.sections()}
{'A': {'x': '1', 'y': '2', 'z': '3'}, 'B': {'a': '4', 'b': '5', 'c': '6'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.