-1

I have Db.ini files and i want to read and write the file as a section using python's configparser.Can anyone explain me how to read and write the config file as a section using configparser?

Db.ini
[mysql]
host = localhost
user = user7
passwd = s$cret
db = ydb

[postgresql]
host = localhost
user = user8
passwd = mypwd$7
db = testdb
5
  • Doubt part: "how to write the config file"? Commented Jul 23, 2019 at 4:57
  • Possible Duplicate: stackoverflow.com/questions/19379120/… Commented Jul 23, 2019 at 4:59
  • yes,how to write the config file Commented Jul 23, 2019 at 4:59
  • So you have .ini file and you want to write this to .config file and then read it? Commented Jul 23, 2019 at 5:01
  • Below I have mentioned the source code,Where I have read the .ini file.Also,I want to write those into the separate file Commented Jul 23, 2019 at 5:07

2 Answers 2

1
import configparser
CONFIG_PATH = '/path/to/Db.ini'  
CONFIG = configparser.RawConfigParser()
CONFIG.read(CONFIG_PATH)

MYSQL_HOST = CONFIG.get('mysql', 'host')
MYSQL_USER = CONFIG.get('mysql', 'user')
...

Check up the official document.

Sign up to request clarification or add additional context in comments.

Comments

0
import configparser

config = configparser.ConfigParser()
config.read('db.ini')
Database1='mysql'
Database2='postgresql'
host = config['Database1']['host']
user = config['Database1']['user']
passwd = config['Database1']['passwd']
db = config['Database1']['db']

print('MySQL configuration:')

print('Host:{host}')
print('User:{user}')
print('Password:{passwd}')
print('Database:{db}')

host2 = config['Database2']['host']
user2 = config['Database2']['user']
passwd2 = config['Database2']['passwd']
db2 = config['Database2']['db']

print('PostgreSQL configuration:')

print('Host: {host2}')
print('User: {user2}')
print('Password: {passwd2}')
print('Database: {db2}')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.