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

[编程基础] Python配置文件读取库ConfigParser总结的更多相关文章

  1. [编程基础] Python谷歌翻译库googletrans总结

    1 使用说明 本文介绍python谷歌翻译库接口googletrans的使用.具体见官方文档: https://py-googletrans.readthedocs.io/en/latest/#goo ...

  2. [编程基础] Python日志记录库logging总结

    Python日志记录教程展示了如何使用日志记录模块在Python中进行日志记录. 文章目录 1 介绍 1.1 背景 1.2 Python日志记录模块 1.3 根记录器 2 Python logging ...

  3. [编程基础] Python数据生成库Faker总结

    Python Faker教程展示了如何使用Faker软件包在Python中生成伪数据.我们使用joke2k/faker包. 1 介绍 Faker是一个生成假数据的Python库.伪数据通常用于测试或用 ...

  4. python配置文件读取

    在代码实现的过程中,我们经常选择将一些固定的参数值写入到一个单独的配置文件中.在python中读取配置文件官方提供了configParser方法. 主要有如下方法(找官文):   (这家伙很懒,直接复 ...

  5. C 构造一个 简单配置文件读取库

    前言 最近看到这篇文章, json引擎性能对比报告 http://www.oschina.net/news/61942/cpp-json-compare?utm_source=tuicool 感觉技术 ...

  6. [编程基础] Python字符串替换笔记

    Python字符串替换笔记 Python字符串替换笔记主要展示了如何在Python中替换字符串.Python中有以下几种替换字符串的方法,本文主要介绍前三种. replace方法(常用) transl ...

  7. [编程基础] Python命令行解析库argparse学习笔记

    Python argparse教程展示了如何使用argparse模块解析Python中的命令行参数. 文章目录 1 使用说明 1.1 Python argparse可选参数 1.2 Python ar ...

  8. linux学习19 shell脚本基础-bash脚本编程基础及配置文件

    一.shell脚本编程 1.编程语言的分类,根据运行方式 a.编译运行:源代码 --> 编译器(编译) --> 程序文件 C语言: b.解释运行:源代码 --> 运行时启动解释器,由 ...

  9. PythonStudy——编程基础 Python Primary

    1.什么是编程语言 语言:  一个事物与另外一个事物沟通的介质 .编程语言是程序员与计算机沟通的介质. 编程: 将人类内识别的语言转化为机器能识别的指令,这种过程就叫做编程. 注:最终这些指令会被转化 ...

随机推荐

  1. 大数据技术之HBase原理与实战归纳分享-上

    @ 目录 概述 定义 特点 数据模型 概述 逻辑结构 物理存储结构 数据模型 应用场景 基础架构 安装 前置条件 部署 启动服务 高可用 Shell操作 基础操作 命令空间 DDL DML 概述 定义 ...

  2. ASCII(American Standard Code for Information Interchange,美国标准信息交换代码)

    ASCII(American Standard Code for Information Interchange,美国标准信息交换代码) ASCII简介 ASCII(American Standard ...

  3. Vue 中为什么要有nextTick?

    摘要:本文将浅析nextTick的作用.使用场景和背后的原理实现,希望对大家有所帮助. 本文分享自华为云社区<Vue 中的 nextTick 有什么作用?>,作者:CoderBin. 一. ...

  4. 12.MongoDB系列之副本集管理

    1. 控制成员状态 1.1 把主节点变为从节点 rs.stepDown() 1.2 阻止选举 如果需要对主节点维护,不想期间其他从节点选举为主节点,则可以 rs.freeze(10000) 维护完成后 ...

  5. Mysql通过Canal同步Elasticsearch

    目录 版本管理 Mysql 设置 在MySQL配置文件my.cnf设置: 检查是否开启 增加新用户: 安装 Elasticsearch es 跨域问题 目录挂载 安装 Elasticsearch-He ...

  6. 一天五道Java面试题----第十天(简述Redis事务实现--------->负载均衡算法、类型)

    这里是参考B站上的大佬做的面试题笔记.大家也可以去看视频讲解!!! 文章目录 1.简述Redis事务实现 2.redis集群方案 3.redis主从复制的核心原理 4.CAP理论,BASE理论 5.负 ...

  7. 齐博x1一段不错的小js提高一点点阅读体验 计算本文阅读所需的时长

    如图所示很多比较大的站点都有这样的一个小玩意 就是本文有多少字 阅读需要多少时间. 一段小小的js就可以实现,当然了php也可以功能太小了不值得做钩子或者插件自己需要的话再模板加一下吧. <sc ...

  8. llinux下mysql建库、新建用户、用户授权、修改用户密码

    1.创建新的数据库 1.1.root用户登录mysql mysql -u root -p  1.2.查看现有数据库 show databases;  1.3.新建数据库,此命名为cjc create ...

  9. MySQL 主从复制一主两从环境配置实战

    MySQL 初始化 MySQL 主从复制是指数据可以从一个 MySQL 数据库服务器主节点复制到一个或多个从节点.MySQL 默认采用异步复制方式;从节点可以复制主数据库中的所有数据库或者特定的数据库 ...

  10. 四、docker容器管理

    一.docker容器管理 1.1 容器查看-ps命令 显示本地容器列表,但是默认不显示关闭的容器,只显示运行中的容器,除非加上命令选项 -a 用法:docker ps [-a 显示所有容器,默认只显示 ...