【问题标题】:ConfigParser instance has no attribute '__setitem__'ConfigParser 实例没有属性“__setitem__”
【发布时间】:2017-01-25 10:34:56
【问题描述】:

我正在尝试初始化配置文件

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__'

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

【问题讨论】:

    标签: python python-2.7 file configuration


    【解决方案1】:
    config.Testing = {"name": "Yohannes", "age": 10}
    

    【讨论】:

    • 这不会向配置中添加任何内容
    【解决方案2】:

    您根本没有正确使用它。 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] 的分配。

    【讨论】:

      【解决方案3】:

      teivaz 的答案是正确的,但可能不完整。您使用 ConfigParser 对象的方式在 Python 3 (docs) 中几乎是正确的,但在 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'}
      

      注意:如果你给它一个非字符串值(例如config.set('Testing', 'age', 10)),Python 2 的ConfigParser.set() 不会抱怨,但是当你尝试检索它时它会抛出一个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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-30
        • 2016-06-29
        • 2012-10-07
        • 2013-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-22
        相关资源
        最近更新 更多