![](/img/trans.png)
[英]Python: Read all config values from .ini file and store in Dictionary and access in other files
[英]Read all the content from .config file & insert into a dictionary with python
我有任何方法可以插入配置文件的所有內容並插入字典中。
配置文件是一個嵌套字典:
[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}}
。
上面是一個示例。我們可以使用泛型(不特定於此配置文件)執行此操作嗎?
使用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.