【发布时间】:2015-01-12 14:36:13
【问题描述】:
; commentary
[owner]
name=Justin Case
organization=Chilling Inc.
[database]
; more commentary
server=192.0.0.1
port=123
file=something.csv
[third section]
attribute=value,
that extends to
the third line,
but not the fourth
给定上面的ini内容,必须构造一个字典,这样
{'owner' : {'name' : 'Justin Case','organization' : 'Chilling Inc.'},
'database' : {'server' : '192.0.0.1', 'port' : '123', 'file' : 'something.csv'},
'third section' : {'attribute' : 'multiline value'}}
我意识到有配置文件解析器,但不允许进行此分配。 目前进展:
with open('ini.txt', encoding='utf8') as data:
lines = [row for row in data]
lines_nocom = []
for row in lines:
if not row.startswith(';'):
lines_nocom.append(row)
dictt = {}
我删除了带有评论的行,因为它们是不必要的。
- 如何让 python 识别这些部分及其各自的属性?
即 section1 可以有 2 个属性,而 section2 可以有任意数量的属性
如果我使用
[row for row in lines_nocom],那么它如何识别一个部分的结束位置和另一个部分的开始位置? - 如何让python识别多行值?
【问题讨论】:
标签: python dictionary ini