使用 ConfigParser 读取没有节名称的文件 [英] Using ConfigParser to read a file without section name

查看:30
本文介绍了使用 ConfigParser 读取没有节名称的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ConfigParser 来读取脚本的运行时配置.

I am using ConfigParser to read the runtime configuration of a script.

我希望可以灵活地不提供节名称(有些脚本足够简单;它们不需要节").ConfigParser 将抛出 NoSectionError 异常,并且不会接受该文件.

I would like to have the flexibility of not providing a section name (there are scripts which are simple enough; they don't need a 'section'). ConfigParser will throw a NoSectionError exception, and will not accept the file.

如何让 ConfigParser 简单地检索配置文件的 (key, value) 元组而没有节名称?

How can I make ConfigParser simply retrieve the (key, value) tuples of a config file without section names?

例如:

key1=val1
key2:val2

我宁愿不写入配置文件.

I would rather not write to the config file.

推荐答案

Alex Martelli 提供了一种解决方案,用于使用 ConfigParser 解析 .properties 文件(显然是无节的配置文件).

Alex Martelli provided a solution for using ConfigParser to parse .properties files (which are apparently section-less config files).

他的解决方案是一个类似文件的包装器,它会自动插入一个虚拟节标题以满足ConfigParser 的要求.

His solution is a file-like wrapper that will automagically insert a dummy section heading to satisfy ConfigParser's requirements.

这篇关于使用 ConfigParser 读取没有节名称的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆