【发布时间】:2022-11-02 18:35:46
【问题描述】:
我要解析和更改的示例 ini 文件。
global_key = global_value
.include other_file.ini
[section]
key = value
有没有办法用 Python 解析和扩充它?我知道通常ConfigParser 建议用于ini 文件,我没有找到任何方法来解析具有全局范围的文件。
【问题讨论】:
我要解析和更改的示例 ini 文件。
global_key = global_value
.include other_file.ini
[section]
key = value
有没有办法用 Python 解析和扩充它?我知道通常ConfigParser 建议用于ini 文件,我没有找到任何方法来解析具有全局范围的文件。
【问题讨论】:
.ini 文件始终为 requires section headers。
在这种情况下,您可以创建自定义节标题并使用 allow_no_value=True 与 ConfigParser 类进行解析。 The allow_no_value=False 允许解析器解析没有值的设置。
>>> string = """
... global_key = global_value
... .include other_file.ini
...
... [section]
... key = value
... """
>>>
>>> from configparser import ConfigParser
>>>
>>> parser = ConfigParser(allow_no_value=True)
>>> parser.read_string("[GLOBAL]
" + string)
>>> for key in parser["GLOBAL"]:
... print(key)
...
global_key
.include other_file.ini
【讨论】: