python读取ini文件所有节点_使用Python将ini文件中的所有内容读入字典

Normally, I code as follows for getting a particular item in a variable as follows

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

Is there any way to read all the contents in a python dictionary?

For example

[A]

x=1

y=2

z=3

[B]

x=1

y=2

z=3

is written into

val["A"]["x"] = 1

...

val["B"]["z"] = 3

解决方案

I suggest subclassing ConfigParser.ConfigParser (or SafeConfigParser, &c) to safely access the "protected" attributes (names starting with single underscore -- "private" would be names starting with two underscores, not to be accessed even in subclasses...):

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

This emulates the usual logic of config parsers, and is guaranteed to work in all versions of Python where there's a ConfigParser.py module (up to 2.7, which is the last of the 2.* series -- knowing that there will be no future Python 2.any versions is how compatibility can be guaranteed;-).

If you need to support future Python 3.* versions (up to 3.1 and probably the soon forthcoming 3.2 it should be fine, just renaming the module to all-lowercase configparser instead of course) it may need some attention/tweaks a few years down the road, but I wouldn't expect anything major.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值