0

我收到了一个关于如何将配置文件解析为字典的好片段,但我似乎无法找到为什么它无法解析我的配置文件(因为我在评论之外没有任何元组)

我的错误信息,

Traceback (most recent call last):   File "test2.py", line 9, in
<module>
    CONFIG_DATA[section_name][item_name] = cfg.get(section_name, item_name)   File "C:\Python27\lib\ConfigParser.py", line 614, in get
    option = self.optionxform(option)   File "C:\Python27\lib\ConfigParser.py", line 374, in optionxform
    return optionstr.lower() AttributeError: 'tuple' object has no attribute 'lower'

编码,

import ConfigParser
from pprint import pprint
cfg = ConfigParser.ConfigParser()
cfg.read('config2.cfg')
CONFIG_DATA = {}
for section_name in cfg.sections():
    CONFIG_DATA[section_name] = {}
    for item_name in cfg.items(section_name):
        CONFIG_DATA[section_name][item_name] = cfg.get(section_name, item_name)
pprint(CONFIG_DATA)

我的配置文件, http ://pastebin.com/UKnrXFGR

4

1 回答 1

2

ConfigParser.items(section[, raw[, vars]])

返回(name, value)给定部分中每个选项的对列表。可选参数与方法的含义相同get()

要么做:

for item_name in cfg.options(section_name): # Note `options`
    CONFIG_DATA[section_name][item_name] = cfg.get(section_name, item_name)

或者:

for item_name, item_value in cfg.items(section_name):
    CONFIG_DATA[section_name][item_name] = item_value
于 2013-06-12T09:23:53.970 回答