pythonpython-3.xsecurityconfigparser

How to read and get the stored value from ini file in python script?


import configparser
config= configparser.ConfigParser()

config.read(r'C:\Users\PycharmProjects\Integration\local.ini')
print(config.sections())

Don't know what to do after this. I had tried this code

server = config.get('db','server') 

It throws an output from print statement and an error.

['"db"', '"Auth"']
configparser.NoSectionError: No section: 'db'

local.ini file contains
["db"]
server=raj
log=ere2
["Auth"]
login=hi

Solution

  • Make ini file like this:

    [db]
    server=raj
    log=ere2
    [Auth]
    login=hi
    

    and import like:

    import configparser
    config= configparser.ConfigParser()
    config.read(r'C:\Users\PycharmProjects\Integration\local.ini')
    server = config['db']['server']
    

    Or if you want the returned data to always be str, use:

    server = str(config['db']['server'])