2016-09-17 110 views
0

我试图初始化配置文件 ConfigParser实例没有属性“__setitem__”

import ConfigParser 

config = ConfigParser.ConfigParser() 
config['Testing'] = {"name": "Yohannes", "age": 10} 
with open("test.ini", "w") as configFile: 
    config.write(configFile) 

,但它不断抛出这个错误

Traceback (most recent call last): 
    File "C:\Users\user\workspace\ObjectDetection\src\confWriter.py", line 9, in <module> 
    config['Testing'] = {"name": "Yohannes", "age": 10} 
AttributeError: ConfigParser instance has no attribute '__setitem__' 

我到处搜寻,但没有找到任何东西

回答

-1
config.Testing = {"name": "Yohannes", "age": 10} 
+0

这不会增加任何配置 – teivaz

0

您根本没有正确使用它。 Here你可以找到例子。

config = ConfigParser.ConfigParser() 
config.add_section('Testing') 
config.set('Testing', 'name', 'Yohannes') 
config.set('Testing', 'age', 10) 

关于你得到你可以阅读here错误:

object.__setitem__(self, key, value) 调用来实现对self[key]分配。

2

teivaz的答案是正确的,但可能不完整。您在Python 3(docs)中使用ConfigParser对象的方式几乎是正确的,但Python 2(docs)不是。

这里是Python的2:

import ConfigParser 
config = ConfigParser.ConfigParser() 
config.add_section('Testing') 
config.set('Testing', 'name', 'Yohannes') 
config.set('Testing', 'age', '10') # note: string value for '10'! 

和Python 3:

import configparser # note: lowercase module name 
config = configparser.ConfigParser() 
config['Testing'] = {'name': 'Yohannes', 'age': '10'} 

注:Python 2里,如果你给它一个非字符串值的ConfigParser.set()不会抱怨(如config.set('Testing', 'age', 10))但是当您尝试检索它时它会抛出TypeError。当您使用带有非字符串值的set()方法时,Python 3将抛出TypeError,但它会悄悄地将值转换为具有__setitem__访问权限的字符串。例如:

config['Testing'] = {'name': 'Yohannes', 'age': 10} # int value for 'age' 
config['Testing']['age'] # returns '10' as a string, not an int 
相关问题