python - 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?
解决方案
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"))
推荐阅读
- pandas - 加入熊猫的专栏
- flutter - 按下时调整容器大小(隐藏和显示其他小部件)
- seo - Googlebot 无法加载页面资源
- jupyter-notebook - 如何在 Jupyter Notebook 的 Markdown 单元格中定义 LaTeX 宏?
- php - 即使项目在数组中,也总是收到错误消息
- c# - 如何比较两个列表以确定它们是否在同一索引上具有所需的值
- android - Android cameraX 分析器 ImageProxy 尺寸
- reactjs - 当用户直接打开详细信息页面时,如何获取项目的详细信息?
- google-cloud-platform - 使用 https 在谷歌云上设置网页
- vb.net - 如何使用 vb.net 代码处理来自 Microsoft SQL Server 数据库的多个空图像值