Search code examples
pythonconfigconfigparser

configparser NoSectionError Python


I have made a config file named "config.cfg" that's on the same folder of my .py file. My config file is like this:

[NetAccess]
host=localhost
port=3306

[Credentials]
username=myuser
password=mypass

[Database]
name=mydb

in my .py file I have this code:

import configparser
config = configparser.ConfigParser()
config.read('config.cfg')
__DBMSuser = config.get('Credentials', 'username')
__DBMSpsw = config.get('Credentials', 'password')

When I launch my program, I receive this error:

configparser.NoSectionError: No section: 'Credentials'

Can someone help me?


Solution

  • I've solved it. My code was correct, and the .cfg file was correctly saved in the folder of my program, but because of other parts of my code, my current directory changed to "C:/Windows/Service32". Not reading the file, I had not error until I was trying to read the sections, so I got NoSectionError. To solve it, I've choice a standard folder (in AppData) where to save my file and read it and then I've used the absolute path.