ini文件数据字典

Dictionary of ini file data

; 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 = {}

我删除了其中带有注释的行,因为它们是不必要的。

  1. 如何让 python 识别这些部分及其各自的属性? 即 section1 可以有 2 个属性,section2 可以有任意数量的属性 如果我这样做 [row for row in lines_nocom] 那么它如何识别一个部分的结束位置和另一个部分的开始位置?
  2. 如何让 python 识别多行值?

跟踪当前部分并将您的密钥添加到该部分;每次使用方括号找到一行时,都会创建一个新部分。

对于续行,做类似的事情;跟踪最后使用的名称:

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'}}