【问题标题】:Reading config file that does not begin with section读取不以section开头的配置文件
【发布时间】:2020-01-23 17:41:01
【问题描述】:

我的配置文件看起来像:

#some text 
host=abc
context=/abc
user=abc
pw=abc

#some text
[dev]
host=abc
context=/abc
user=abc
pw=abc

[acc]
host=abc
context=/abc
user=abc
pw=abc

我想在 Python 2.7 中使用 ConfigParser 解析 cfg 文件。问题是 cfg 文件不以该部分开头。我无法删除部分之前的文本行。有什么解决办法吗?

【问题讨论】:

  • 您可能会在解析文件之前注入一个部分,但这对我来说听起来很hacky。我宁愿建议你看看ConfigObj 包。更加灵活,并且允许解析没有标头的键。我在大部分项目中都使用它,而且我个人永远不会再使用ConfigParser

标签: python python-2.7 configparser


【解决方案1】:

注入您选择的部分标题。

import ConfigParser
import StringIO


def add_header(cfg, hdr="DEFAULT"):
    s = StringIO.StringIO()
    s.write("[{}]\n".format(hdr))
    for line in cfg:
        s.write(line)
    s.seek(0)
    return s


parser = ConfigParser.ConfigParser()
with open('file.cfg') as cfg:
    parser.readfp(add_header(cfg, "foo"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 2015-06-14
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多