首页 > 解决方案 > Reading config file that does not begin with section

问题描述

I have config file that looks something like:

#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

I would like to parse the cfg file with ConfigParser in Python 2.7. The problem is that the cfg file does not start with the section. I cannot delete the text lines before the sections. Is there any workaround for that?

标签: pythonpython-2.7configparser

解决方案


Inject a section header of your choice.

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

推荐阅读