Python Config Parser can't find section?

16.9k views Asked by At

I'm trying to use ConfigParser to read a .cfg file for my pygame game. I can't get it to function for some reason. The code looks like this:

import ConfigParser
def main():
    config = ConfigParser.ConfigParser()
    config.read('options.cfg')
    print config.sections()
    Screen_width = config.getint('graphics','width')
    Screen_height = config.getint('graphics','height')

The main method in this file is called in the launcher for the game. I've tested that out and that works perfectly. When I run this code, I get this error:

Traceback (most recent call last):
  File "Scripts\Launcher.py", line 71, in <module>
    Game.main()
  File "C:\Users\astro_000\Desktop\Mini-Golf\Scripts\Game.py", line 8, in main
    Screen_width = config.getint('graphics','width')
  File "c:\python27\lib\ConfigParser.py", line 359, in getint
    return self._get(section, int, option)
  File "c:\python27\lib\ConfigParser.py", line 356, in _get
    return conv(self.get(section, option))
  File "c:\python27\lib\ConfigParser.py", line 607, in get
    raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'graphics'

The thing is, there is a section 'graphics'.

The file I'm trying to read from looks like this:

[graphics]
height = 600
width = 800

I have verified that it is, in fact called options.cfg. config.sections() returns only this: "[]"

I've had this work before using this same code, but it wont work now. Any help would be greatly appreciated.

3

There are 3 answers

4
tamasgal On BEST ANSWER

I always use the SafeConfigParser:

from ConfigParser import SafeConfigParser

def main():
    parser = SafeConfigParser()
    parser.read('options.cfg')
    print(parser.sections())
    screen_width = parser.getint('graphics','width')
    screen_height = parser.getint('graphics','height')

Also make sure there is a file called options.cfg and specify the full path if needed, as I already commented. Parser will fail silently if there is no file found.

7
k-nut On

Your config file probably is not found. The parser will just produce an empty set in that case. You should wrap your code with a check for the file:

from ConfigParser import SafeConfigParser
import os

def main():
    filename = "options.cfg"
    if os.path.isfile(filename):
        parser = SafeConfigParser()
        parser.read(filename)
        print(parser.sections())
        screen_width = parser.getint('graphics','width')
        screen_height = parser.getint('graphics','height')
    else:
        print("Config file not found")

if __name__=="__main__":
    main()
0
user12104284 On

I was also facing the same issue. I had moved my project to a different location and assumed it will work fine. But after executing the code in new location it was not able to find my configuration file and throwing error:

Exception: Section postgresql_conn_config not found in the database.ini file

Resolution: provide the full path of the file and put debug statements correctly to identify the issue. Below is my code. Hope it helps:

from configparser import ConfigParser
import os


def get_connection_by_config(filename='database.ini',section='postgresql_conn_config'):
'''
    This method will use the connection data saved in configuration file to get postgresql database server connection.

    filename : Is the configuration file saved path, the configuration file is database.ini in this example, and it is saved in the same path of PostgresqlManager.py file.

    section_name : This is the section name in above configuration file. The options in this section record the postgresql database server connection info.

'''

# create a parser
parser = ConfigParser()

# define the file path
loc = '/src/data_engineering/'
cwd = os.path.abspath(os.getcwd()).replace('\\', '/')
path = cwd+loc
filename_ = path+filename
db = {}

#check file path 
if os.path.isfile(filename_):

    # read config file
    parser.read(filename_)

    # get section
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            db[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))

else:
    raise Exception("File {} not found in location".format(filename_))

return db