将ConfigParser.items('')转换为字典

如何将ConfigParser.items(’section’)的结果转换为字典以格式化字符串,如下所示:

import ConfigParser

config = ConfigParser.ConfigParser()

config.read('conf.ini')

connection_string = ("dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' "

"password='%(password)s' port='%(port)s'")

print connection_string % config.items('db')

回答:

实际上,您已经在中完成了此操作config._sections。例:

$ cat test.ini

[First Section]

var = value

key = item

[Second Section]

othervar = othervalue

otherkey = otheritem

接着:

>>> from ConfigParser import ConfigParser

>>> config = ConfigParser()

>>> config.read('test.ini')

>>> config._sections

{'First Section': {'var': 'value', '__name__': 'First Section', 'key': 'item'}, 'Second Section': {'__name__': 'Second Section', 'otherkey': 'otheritem', 'othervar': 'othervalue'}}

>>> config._sections['First Section']

{'var': 'value', '__name__': 'First Section', 'key': 'item'}

我同样的问题溶液downvoted所以我会进一步说明我的答案是如何做同样的事情,而不必直通部分dict(),因为config._sections

由模块为您已经提供

[db]

dbname = testdb

dbuser = test_user

host = localhost

password = abc123

port = 3306

发生的魔法:

>>> config.read('test.ini')

['test.ini']

>>> config._sections

{'db': {'dbname': 'testdb', 'host': 'localhost', 'dbuser': 'test_user', '__name__': 'db', 'password': 'abc123', 'port': '3306'}}

>>> connection_string = "dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' password='%(password)s' port='%(port)s'"

>>> connection_string % config._sections['db']

"dbname='testdb' user='test_user' host='localhost' password='abc123' port='3306'"

因此,这种解决方案 错,实际上只需要少一步。感谢您的光临!

以上是 将ConfigParser.items('')转换为字典 的全部内容, 来源链接: utcz.com/qa/417061.html

回到顶部