[编程基础] 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 参考
[编程基础] Python配置文件读取库ConfigParser总结的更多相关文章
- [编程基础] Python谷歌翻译库googletrans总结
1 使用说明 本文介绍python谷歌翻译库接口googletrans的使用.具体见官方文档: https://py-googletrans.readthedocs.io/en/latest/#goo ...
- [编程基础] Python日志记录库logging总结
Python日志记录教程展示了如何使用日志记录模块在Python中进行日志记录. 文章目录 1 介绍 1.1 背景 1.2 Python日志记录模块 1.3 根记录器 2 Python logging ...
- [编程基础] Python数据生成库Faker总结
Python Faker教程展示了如何使用Faker软件包在Python中生成伪数据.我们使用joke2k/faker包. 1 介绍 Faker是一个生成假数据的Python库.伪数据通常用于测试或用 ...
- python配置文件读取
在代码实现的过程中,我们经常选择将一些固定的参数值写入到一个单独的配置文件中.在python中读取配置文件官方提供了configParser方法. 主要有如下方法(找官文): (这家伙很懒,直接复 ...
- C 构造一个 简单配置文件读取库
前言 最近看到这篇文章, json引擎性能对比报告 http://www.oschina.net/news/61942/cpp-json-compare?utm_source=tuicool 感觉技术 ...
- [编程基础] Python字符串替换笔记
Python字符串替换笔记 Python字符串替换笔记主要展示了如何在Python中替换字符串.Python中有以下几种替换字符串的方法,本文主要介绍前三种. replace方法(常用) transl ...
- [编程基础] Python命令行解析库argparse学习笔记
Python argparse教程展示了如何使用argparse模块解析Python中的命令行参数. 文章目录 1 使用说明 1.1 Python argparse可选参数 1.2 Python ar ...
- linux学习19 shell脚本基础-bash脚本编程基础及配置文件
一.shell脚本编程 1.编程语言的分类,根据运行方式 a.编译运行:源代码 --> 编译器(编译) --> 程序文件 C语言: b.解释运行:源代码 --> 运行时启动解释器,由 ...
- PythonStudy——编程基础 Python Primary
1.什么是编程语言 语言: 一个事物与另外一个事物沟通的介质 .编程语言是程序员与计算机沟通的介质. 编程: 将人类内识别的语言转化为机器能识别的指令,这种过程就叫做编程. 注:最终这些指令会被转化 ...
随机推荐
- emqx启用JWT令牌认证(包含hmac-based和public-key)
emqx连接启用jwt令牌认证 jwt令牌 概述 JWT 即 JSON Web Tokens 是一种开放的,用于在两方之间安全地表示声明的行业标准的方法(RFC 7519). 组成 令牌的形式 xxx ...
- 5.ElasticSearch系列之文档的基本操作
1. 文档写入 # create document. 自动生成 _id POST users/_doc { "user" : "shenjian", " ...
- 怎么在线预览.doc,.docx,.ofd,.pdf,.wps,.cad文件以及Office文档的在线解析方式。
前言 Office文件在线预览是目前移动化办公的一种新趋势.Office在线预览指的是Office系列的文件在线查看而不依附域客户端的存在.在浏览器或者浏览器控件中可以预览查看Word.PDF.Exc ...
- 齐博x1如何开启自定义标签模板功能
为安全起见,同时也为了避免用户随意添加风格导致默认模板不协调,系统默认关闭了类似V系列的自定义修改模板功能.如下图所示,默认是关闭的 你如果需要启用的话,把下面的代码,参考下图导进去后,就可以增加一个 ...
- RedHat7.6安装mysql8步骤
1.官网下载mysql安装包 直达链接:https://dev.mysql.com/downloads/mysql/ 2.将下载好的安装包上传到redhat系统上(有多种上传方式,本次使用Sec ...
- LcdTools如何通过PX01把EDP屏的EDID拷贝出来
PX01点EDP屏在上电过程会自动读取屏EDID,怎么把EDP EDID值拷贝出来呢? 在上电时序函数调用SetEdidRdShowEn(ON)指令开启EDID值读取显示功能.如下图 通过上述操作开机 ...
- 7.websocket收发消息
客户端主动向服务端发起websocket连接,服务端接收到连接后通过(握手) 客户端 websocket socket = new WebSocket('ws://127.0.0.1/ws/'); 服 ...
- virtualenv +virtualenvwrapper
一.虚拟环境virtualenv 1.安装:pip3 install virtualenv 2.创建虚拟环境:virtualenv venv #venv为虚拟环境目录名,目录名自定义 #virtual ...
- JWT中token的理解
今天我们来聊一聊关于JWT授权的事情. JWT:Json Web Token.顾名思义,它是一种在Web中,使用Json来进行Token授权的方案. 既然没有找好密码,token是如何解决信任问题的呢 ...
- JAVA学习前准备
电脑常用快捷键 Ctrl+C:复制 Ctrl+V:粘贴 Ctrl+A:全选 Ctrl+X:剪切 Ctrl+Z:撤销 Ctrl+S:保存 Alt+F4:关闭窗口 Shift+delete:永久性删除文件 ...