简体   繁体   中英

How to read and write INI files as a section using python configparser?

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
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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM