Raj
Raj

Reputation: 623

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

Upvotes: 1

Views: 8332

Answers (3)

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

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'])

Upvotes: 6

PyHP3D
PyHP3D

Reputation: 88

For anyone who may encounter this and the accepted solution doesn't work for them, Rohit-Pandley's answer is probably correct except for 2 small syntax errors where "config['db']['server')]" is used.

The ")" in the 'server' key call (inside the []) is not supposed to be there. It should read like this instead.

server = config['db']['server']

and

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

So altogether it should look like this. (This is Rohit-Pandley's solution copied and fixed)

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 it return always str so if data type is other then string then use:

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

Upvotes: 1

Raj
Raj

Reputation: 623

['"db"', '"Auth"']

Answer: 
["db","Auth"]

Upvotes: 0

Related Questions