我有 Db.ini 文件,我想使用 python 的 configparser 将文件作为一个部分读取和写入。谁能解释我如何使用 configparser 将配置文件作为一个部分读取和写入?
Db.ini
[mysql]
host = localhost
user = user7
passwd = s$cret
db = ydb
[postgresql]
host = localhost
user = user8
passwd = mypwd$7
db = testdb
我有 Db.ini 文件,我想使用 python 的 configparser 将文件作为一个部分读取和写入。谁能解释我如何使用 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')
...
查看官方文档。
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}')