Error raise KeyError(key) with configparser

Question:

I am trying to write a database application with Python3 using an INI file to store connection settings. If the file does not exist, the script ought to create it using an IF statement. The code that I have is below:

import configparser, os

if os.path.exists("main.ini"):
    config = configparser.ConfigParser()
    with open("main.ini", "r") as connect:
        print(connect)
else:
    config = configparser.ConfigParser()
    host=input("Hostname... ")
    user=input("Username... ")
    pwrd=input("Password... ")
    base=input("Basename... ")
    config['connect']['host'] = host
    config['connect']['user'] = user
    config['connect']['pass'] = pwrd
    config['connect']['base'] = base
    with open("main.ini", "w") as info:
        config.write(info)

The error that I am getting is raise KeyError(key)
KeyError: ‘connect’

Expecting it to create an INI file with settings supplied by user. Tried googling the issue and putting filename in variable and changing it

Asked By: wrichards853

||

Answers:

Create the following before adding values:

config['connect'] = {}             # Create the section in .INI
config['connect']['host'] = host
...

The whole section with variables can be created by passing a filled-out dictionary as well.

config['connect'] = {'host': host,
                     'user': user,
                     'pass': pwrd,
                     'base': base}

See The Python documentation for configparser.

Answered By: Mark Tolonen
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.