微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[编程基础] 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐