栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将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'"

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/516878.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号