打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

2023.10.31 浙江

关注

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

文章目录

  • 1 介绍
  • 1.1 Python ConfigParser读取文件
  • 1.2 Python ConfigParser中的节
  • 1.3 Python ConfigParser从字符串中读取数据
  • 1.4 Python ConfigParser从字典中读取数据
  • 1.5 Python ConfigParser写入数据
  • 1.6 Python ConfigParserj解释数据
  • 2 参考

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 = localhostuser = user7passwd = s$cretdb = ydb[postgresql]host = localhostuser = user8passwd = mypwd$7db = testdb

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

import configparser# 启动ConfigParseconfig = 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: localhostUser: user7Password: s$cretDatabase: ydbPostgreSQL configuration:Host: localhostUser: user8Password: mypwd$7Database: testdb

1.2 Python ConfigParser中的节

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

import configparserconfig = 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 mysqlConfig file has section postgresqlConfig file does not have section sqlite

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

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

import configparser# 字符串配置文件数据cfg_data = '''[mysql]host = localhostuser = user7passwd = s$cretdb = 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: localhostUser: user7Password: s$cretDatabase: 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: localhostUser: user7Password: s$cretDatabase: ydb

1.5 Python ConfigParser写入数据

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

import configparserconfig = 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 = localhostuser = user7passwd = s$cretdb = ydb

1.6 Python ConfigParserj解释数据

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

[info]users_dir= /home/ubuntuname= Janohome_dir= %(users_dir)s\%(name)s

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

import configparserconfig = 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/ubuntuName: JanoHome directory: /home/ubuntu/Jano

2 参考

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

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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
深入探讨Python ConfigParser模块正确应用方式
python3操作INI格式文件
[快学Python3]INI文件读写
Python配置文件模块埋个坑,险些影响了版本上线!
Python常用配置文件ini、json、yaml读写总结
Python中让MySQL查询结果返回字典类型的方法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服