我很早就收到了如何将配置文件解析为字典的好消息,但我似乎无法找到为什么它无法解析我的配置文件(因为我在评论之外没有任何元组)
我的错误信息,
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
答案 0 :(得分: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