读取不以section开头的配置文件

Reading config file that does not begin with section

我的配置文件类似于:

#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 文件不是以 section 开头的。我无法删除这些部分之前的文本行。有什么解决方法吗?

插入您选择的部分 header。

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"))