通常情况下,我按如下方式编写代码,以获取变量中的特定项目,如下所示
try:
config = ConfigParser.ConfigParser()
config.read(self.iniPathName)
except ConfigParser.MissingSectionHeaderError, e:
raise WrongIniFormatError(`e`)
try:
self.makeDB = config.get("DB","makeDB")
except ConfigParser.NoOptionError:
self.makeDB = 0
有什么方法可以读取Python 目录中的所有内容吗?
例如
[A]
x=1
y=2
z=3
[B]
x=1
y=2
z=3
写成
val["A"]["x"] = 1
...
val["B"]["z"] = 3
发布于 2018-02-28 09:56:19
我建议子类化ConfigParser.ConfigParser
(或SafeConfigParser
,&c)安全地访问“受保护的”属性(以单下划线开头的名称 - “private”将以两个下划线开头,即使在子类中也不会被访问):
import ConfigParser
class MyParser(ConfigParser.ConfigParser):
def as_dict(self):
d = dict(self._sections)
for k in d:
d[k] = dict(self._defaults, **d[k])
d[k].pop('__name__', None)
return d
这模拟了配置解析器的通常逻辑,并且保证可以在所有版本的Python中工作,其中有一个ConfigParser.py
模块(高达2.7,这是该2.*
系列的最后一个- 知道将来没有Python 2.any版本是如何保证兼容性;-)。
如果需要支持未来的Python 3.*
版本(最高3.1,可能即将推出的3.2版本应该没问题,只需将模块重命名为全小写configparser
)。
发布于 2018-02-28 11:43:09
dictionary = {}
for section in config.sections():
dictionary[section] = {}
for option in config.options(section):
dictionary[section][option] = config.get(section, option)
https://stackoverflow.com/questions/-100007449
复制相似问题