[编程基础] Python配置文件读取库ConfigParser总结

Python ConfigParser教程显示了如何使用ConfigParser在Python中使用配置文件。

1 介绍

ConfigParser是一个Python类,为Python程序实现基本的配置语言。它提供类似于Microsoft Windows INI文件的结构。ConfigParser允许编写可由最终用户轻松定制的Python程序。

配置文件由选项的键/值对组成。节名由[]字符分隔。这些键值对用:或=分隔。注释以#或;开头。

具体使用文档见:
https://docs.python.org/3/library/configparser.html

本文所用python语言环境为python3。python2和python3中configparser包名不一样。
configparser为python3中的包名
ConfigParser为python2中的包名

1.1 Python ConfigParser读取文件

在下面示例中,我们从文件中读取配置数据。配置文件db.ini内容如下。由两部分数据组成。

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

[postgresql]
host = localhost
user = user8
passwd = mypwd$7
db = testdb

以下示例读取MySQL和PostgreSQL的配置数据。

import configparser

# 启动ConfigParse
config = configparser.ConfigParser()
# 使用read()读取文件。
config.read('db.ini')

# 从mysql部分访问数据
host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print('MySQL configuration:')

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

# 从postgresql部分访问数据
host2 = config['postgresql']['host']
user2 = config['postgresql']['user']
passwd2 = config['postgresql']['passwd']
db2 = config['postgresql']['db']

print('PostgreSQL configuration:')

print(f'Host: {host2}')
print(f'User: {user2}')
print(f'Password: {passwd2}')
print(f'Database: {db2}')
MySQL configuration:
Host: localhost
User: user7
Password: s$cret
Database: ydb
PostgreSQL configuration:
Host: localhost
User: user8
Password: mypwd$7
Database: testdb

1.2 Python ConfigParser中的节

配置数据分为多个节。在sections()读取所有节和has_section()检查是否有指定的节。

import configparser

config = configparser.ConfigParser()
config.read('db.ini')

# 获得节名
sections = config.sections()
print(f'Sections: {sections}')

sections.append('sqlite')

for section in sections:

    # 判断是否有该节名
    if config.has_section(section):
      print(f'Config file has section {section}')
    else:
      print(f'Config file does not have section {section}')
Sections: ['mysql', 'postgresql']
Config file has section mysql
Config file has section postgresql
Config file does not have section sqlite

1.3 Python ConfigParser从字符串中读取数据

从Python 3.2开始,我们可以使用read_string()方法从字符串读取配置数据。

import configparser

# 字符串配置文件数据
cfg_data = '''
[mysql]
host = localhost
user = user7
passwd = s$cret
db = ydb
'''

config = configparser.ConfigParser()
config.read_string(cfg_data)

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print(f'Host: {host}')
print(f'User: {user}')
print(f'Password: {passwd}')
print(f'Database: {db}')
Host: localhost
User: user7
Password: s$cret
Database: ydb

1.4 Python ConfigParser从字典中读取数据

从Python 3.2开始,我们可以使用read_dict()方法从字典中读取配置数据。

import configparser

# 字典数据
# 键是节名,值是带有该节中存在的键和值的字典。
cfg_data = {
    'mysql': {'host': 'localhost', 'user': 'user7',
              'passwd': 's$cret', 'db': 'ydb'}
}

config = configparser.ConfigParser()
config.read_dict(cfg_data)

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print(f'Host: {host}')
print(f'User: {user}')
print(f'Password: {passwd}')
print(f'Database: {db}')
Host: localhost
User: user7
Password: s$cret
Database: ydb

1.5 Python ConfigParser写入数据

可以通过write()方法写入配置数据。以下示例将配置数据写入db3.ini文件。

import configparser

config = configparser.ConfigParser()

# 通过add_section()函数添加键
config.add_section('mysql')

config['mysql']['host'] = 'localhost'
config['mysql']['user'] = 'user7'
config['mysql']['passwd'] = 's$cret'
config['mysql']['db'] = 'ydb'

# 写入数据
with open('db3.ini', 'w') as configfile:
    config.write(configfile)

db.ini中的内容如下:

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

1.6 Python ConfigParserj解释数据

ConfigParser允许在配置文件中解释数据。它使用%()语法。本示例用到cfg.ini如下:

[info]
users_dir= /home/ubuntu
name= Jano
home_dir= %(users_dir)s\%(name)s

我们用插值来构建home_dir。注意,“s”字符是语法的一部分。我们将解释数据

import configparser

config = configparser.ConfigParser()
config.read('cfg.ini')

users_dir = config['info']['users_dir']
name = config['info']['name']
home_dir = config['info']['home_dir']

# 读取用户路径
print(f'Users directory: {users_dir}')
# 读取用户名
print(f'Name: {name}')
# 读取完整路径
print(f'Home directory: {home_dir}')
Users directory: /home/ubuntu
Name: Jano
Home directory: /home/ubuntu/Jano

2 参考

http://zetcode.com/python/configparser/

https://docs.python.org/3/library/configparser.html

https://www.cnblogs.com/plf-Jack/p/11170284.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值