Search code examples
pythonconfigparser

ConfigParser instance has no attribute '[extension]'


I am learning python and I am trying to do a simple task of reading information from a config file.

So using the Python Doc and this similar problem as a reference I created two files.

This is my config file config.ini (also tried config.cfg)

[DEFAULT]
OutDir = path_to_file/

[AUTH]
TestInt = 100
TestStr = blue
TestParse = blua

and this is my python file test.py

import ConfigParser

from ConfigParser import *
config = ConfigParser()

config.read(config.cfg)

for name in config.options('AUTH'):
    print name

out = config.get('DEFAULT', 'OutDir')
print 'Output directory is ' + out

however when running the command python test.py I am erroring out and receiving this error

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    config.read(config.cfg)
AttributeError: ConfigParser instance has no attribute 'cfg'

Note: I thought that meant it the extension couldn't be read so I created the .ini file and changed it in the code and I received the same error but it instead read ...has no attribute 'ini'

I am not sure what I am doing wrong since I am doing the exact same as the python doc and the solution someone used to fix this similar issue.


Solution

  • config.read takes a string as its argument. You forgot to quote the file name, and config was coincidentally the name of a Python object (the module) that potentially could have a cfg attribute. You'd get an entirely different error if you had written config.read(foobarbaz.ini).

    The correct line is

    config.read('config.cfg')  # or 'config.ini', if that's the file name