【问题标题】:Python parsing ini file with global scope/propertiesPython解析具有全局范围/属性的ini文件
【发布时间】:2022-11-02 18:35:46
【问题描述】:

我要解析和更改的示例 ini 文件。

global_key = global_value
.include other_file.ini

[section]
key = value

有没有办法用 Python 解析和扩充它?我知道通常ConfigParser 建议用于ini 文件,我没有找到任何方法来解析具有全局范围的文件。

【问题讨论】:

    标签: python ini


    【解决方案1】:

    .ini 文件始终为 requires section headers

    在这种情况下,您可以创建自定义节标题并使用 allow_no_value=TrueConfigParser 类进行解析。 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
    

    【讨论】:

      猜你喜欢
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 2019-03-09
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多