Home > Software design >  Error raise KeyError(key) with configparser
Error raise KeyError(key) with configparser

Time:10-30

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

CodePudding user response:

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.

  • Related