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

将ConfigParser.items('')转换为字典,第1张

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

实际上,您已经在中完成了此 *** 作

config._sections
。例:

$ cat test.ini[First Section]var = valuekey = item[Second Section]othervar = othervalueotherkey = 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

由模块为您已经提供

示例test.ini:

[db]dbname = testdbdbuser = test_userhost   = localhostpassword = abc123port   = 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'"

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



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5508085.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存