[编程基础] Python配置文件读取库ConfigParser总结
itomcoil 2025-10-19 06:01 1 浏览
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 = 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
相关推荐
- python创建文件夹,轻松搞定,喝咖啡去了
-
最近经常在录视频课程,一个课程下面往往有许多小课,需要分多个文件夹来放视频、PPT和案例,这下可好了,一个一个手工创建,手酸了都做不完。别急,来段PYTHON代码,轻松搞定,喝咖啡去了!import...
- 如何编写第一个Python程序_pycharm写第一个python程序
-
一、第一个python程序[掌握]python:python解释器,将python代码解释成计算机认识的语言pycharm:IDE(集成开发环境),写代码的一个软件,集成了写代码,...
- Python文件怎么打包为exe程序?_python3.8打包成exe文件
-
PyInstaller是一个Python应用程序打包工具,它可以将Python程序打包为单个独立可执行文件。要使用PyInstaller打包Python程序,需要在命令行中使用py...
- 官方的Python环境_python环境版本
-
Python是一种解释型编程开发语言,根据Python语法编写出来的程序,需要经过Python解释器来进行执行。打开Python官网(https://www.python.org),找到下载页面,选择...
- [编程基础] Python配置文件读取库ConfigParser总结
-
PythonConfigParser教程显示了如何使用ConfigParser在Python中使用配置文件。文章目录1介绍1.1PythonConfigParser读取文件1.2Python...
- Python打包exe软件,用这个库真的很容易
-
初学Python的人会觉得开发一个exe软件非常复杂,其实不然,从.py到.exe文件的过程很简单。你甚至可以在一天之内用Python开发一个能正常运行的exe软件,因为Python有专门exe打包库...
- 2025 PyInstaller 打包说明(中文指南),python 打包成exe 都在这里
-
点赞标记,明天就能用上这几个技巧!linux运维、shell、python、网络爬虫、数据采集等定定做,请私信。。。PyInstaller打包说明(中文指南)下面按准备→基本使用→常用...
- Python自动化办公应用学习笔记40—文件路径2
-
4.特殊路径操作用户主目录·获取当前用户的主目录路径非常常用:frompathlibimportPathhome_dir=Path.home()#返回当前用户主目录的Path对象...
- Python内置tempfile模块: 生成临时文件和目录详解
-
1.引言在Python开发中,临时文件和目录的创建和管理是一个常见的需求。Python提供了内置模块tempfile,用于生成临时文件和目录。本文将详细介绍tempfile模块的使用方法、原理及相关...
- python代码实现读取文件并生成韦恩图
-
00、背景今天战略解码,有同学用韦恩图展示各个产品线的占比,效果不错。韦恩图(Venndiagram),是在集合论数学分支中,在不太严格的意义下用以表示集合的一种图解。它们用于展示在不同的事物群组之...
- Python技术解放双手,一键搞定海量文件重命名,一周工作量秒搞定
-
摘要:想象一下,周五傍晚,办公室的同事们纷纷准备享受周末,而你,面对着堆积如山的文件,需要将它们的文件名从美国日期格式改为欧洲日期格式,这似乎注定了你将与加班为伍。但别担心,Python自动化办公来...
- Python路径操作的一些基础方法_python路径文件
-
带你走进@机器人时代Discover点击上面蓝色文字,关注我们Python自动化操作文件避开不了路径操作方法,今天我们来学习一下路径操作的一些基础。Pathlib库模块提供的路径操作包括路径的...
- Python爬取下载m3u8加密视频,原来这么简单
-
1.前言爬取视频的时候发现,现在的视频都是经过加密(m3u8),不再是mp4或者avi链接直接在网页显示,都是经过加密形成ts文件分段进行播放。今天就教大家如果通过python爬取下载m3u8加密视频...
- 探秘 shutil:Python 高级文件操作的得力助手
-
在Python的标准库中,shutil模块犹如一位技艺精湛的工匠,为我们处理文件和目录提供了一系列高级操作功能。无论是文件的复制、移动、删除,还是归档与解压缩,shutil都能以简洁高效的方式完成...
- 怎么把 Python + Flet 开发的程序,打包为 exe ?这个方法很简单!
-
前面用Python+Flet开发的“我的计算器v3”,怎么打包为exe文件呢?这样才能分发给他人,直接“双击”运行使用啊!今天我给大家分享一个简单的、可用的,把Flet开发的程序打包为...
- 一周热门
- 最近发表
-
- python创建文件夹,轻松搞定,喝咖啡去了
- 如何编写第一个Python程序_pycharm写第一个python程序
- Python文件怎么打包为exe程序?_python3.8打包成exe文件
- 官方的Python环境_python环境版本
- [编程基础] Python配置文件读取库ConfigParser总结
- Python打包exe软件,用这个库真的很容易
- 2025 PyInstaller 打包说明(中文指南),python 打包成exe 都在这里
- Python自动化办公应用学习笔记40—文件路径2
- Python内置tempfile模块: 生成临时文件和目录详解
- python代码实现读取文件并生成韦恩图
- 标签列表
-
- ps图案在哪里 (33)
- super().__init__ (33)
- python 获取日期 (34)
- 0xa (36)
- super().__init__()详解 (33)
- python安装包在哪里找 (33)
- linux查看python版本信息 (35)
- python怎么改成中文 (35)
- php文件怎么在浏览器运行 (33)
- eval在python中的意思 (33)
- python安装opencv库 (35)
- python div (34)
- sticky css (33)
- python中random.randint()函数 (34)
- python去掉字符串中的指定字符 (33)
- python入门经典100题 (34)
- anaconda安装路径 (34)
- yield和return的区别 (33)
- 1到10的阶乘之和是多少 (35)
- python安装sklearn库 (33)
- dom和bom区别 (33)
- js 替换指定位置的字符 (33)
- python判断元素是否存在 (33)
- sorted key (33)
- shutil.copy() (33)