; 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
鉴于上述内容,必须构建一个字典
{'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 = {}
我删除了带有注释的行,因为它们是不必要的。
[row for row in lines_nocom]
那么它如何识别一个部分的结束而另一个部分的开始?答案 0 :(得分:1)
跟踪当前部分并将密钥添加到该部分;每次使用方括号找到一行时都会创建一个新的部分。
对于延续线,做类似的事情;跟踪上次使用的名称:
with open('ini.txt', encoding='utf8') as data:
section = None # current section
name = None # current name being stored
result = {}
for line in data:
line = line.strip()
if not line or line.startswith(';'):
# skip comments and empty lines
continue
if line.startswith('[') and line.endswith(']'):
# new section
section_name = line.strip('[]')
section = result[section_name] = {}
continue
# add entries to the existing section
if '=' in line:
name, _, value = line.partition('=')
name = name.strip()
section[name] = value.strip()
else:
# adding to last-used name
section[name] += ' ' + line
演示:
>>> from io import StringIO
>>> from pprint import pprint
>>> sample = StringIO('''\
... ; 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
... ''')
>>> section = None # current section
>>> name = None # current name being stored
>>> result = {}
>>> for line in sample:
... line = line.strip()
... if not line or line.startswith(';'):
... # skip comments and empty lines
... continue
... if line.startswith('[') and line.endswith(']'):
... # new section
... section_name = line.strip('[]')
... section = result[section_name] = {}
... continue
... # add entries to the existing section
... if '=' in line:
... name, _, value = line.partition('=')
... name = name.strip()
... section[name] = value.strip()
... else:
... # adding to last-used name
... section[name] += ' ' + line
...
>>> pprint(result)
{'database': {'file': 'something.csv', 'port': '123', 'server': '192.0.0.1'},
'owner': {'name': 'Justin Case', 'organization': 'Chilling Inc.'},
'third section': {'attribute': 'value, that extends to the third line, but '
'not the fourth'}}