Skip to content Skip to sidebar Skip to footer

Python - ConfigParser - AttributeError: ConfigParser Instance Has No Attribute '__getitem__'

I am creating a quote of the day server. I am reading options from an INI file, whose text is below: [Server] host = port = 17 [Quotes] file=quotes.txt However, when I use Config

Solution 1:

After a quick read it seems like you're trying to read the data as if it's a dictionary, when you should use: config.get(section, data)

EG:

...
config = ConfigParser()
config.read(filename)
...
configOptions.port = config.getint('Server', 'port')
configOptions.host = config.get('Server', 'host')
configOptions.quoteFile = config.get('Quotes', 'file')

To write to the config-file you could do something like:

...
def setValue(parser, sect, index, value):
    cfgfile = open(filename, 'w')
    parser.set(sect, index, value)
    parser.write(cfgfile)
    cfgfile.close()

Solution 2:

The included ConfigParser with python 2.7 does not work in this fashion. You can, however, achieve exactly what you've proposed using the back ported configparser module available on PyPy.

pip install configparser

Then you can use it just as you would in Python 3*

from configparser import ConfigParser
parser = ConfigParser()
parser.read("settings.ini")
# or parser.read_file(open("settings.ini"))
parser['Server']['port']
# '17'
parser.getint('Server', 'port')
#  17

NOTE

  • configparser is not 100% compatible with the Python 3 version.
  • The backport is intended to keep 100% compatibility with the vanilla release in Python 3.2+.
  • Using it in this fashion displayed above, will default to the Python 3 implementation if available.

Solution 3:

for python3
iniparser.py

#!/usr/bin/python3
import configparser
import sys

config = configparser.ConfigParser()
config.read(sys.argv[1])
print(config[sys.argv[2]][sys.argv[3]])

using

python iniparser.py <filepath> <section> <key>

Post a Comment for "Python - ConfigParser - AttributeError: ConfigParser Instance Has No Attribute '__getitem__'"