知识预热
什么是 configparser?
configparser
是 Python 标准库中用于读写 INI 格式配置文件 的模块。
它提供了一种 简单、直观、跨平台 的方式来管理程序的配置项。
什么是 INI 文件?
.ini
文件是 Initialization File(初始化文件) 的缩写。
顾名思义,它在程序或系统启动时,提供 初始的配置信息与参数设置。
📘 INI 文件的基本结构
一个典型的 .ini
文件由三部分组成:
组成部分 | 说明 | 示例 |
---|---|---|
节(Section) | 用方括号 [ ] 表示,用于对配置项进行分组。 |
[Database] , [Server] , [User] |
键(Key) | 表示某个具体的配置项名称,也称“属性(Property)”。 | host , port , username |
值(Value) | 为键赋予的具体内容。 | localhost , 8080 , admin |
📄 基本语法结构
[节名]
键 = 值
🧩 示例:一个典型的配置文件
[Graphics]
resolution = 1920x1080
fullscreen = True[Audio]
volume = 80
mute = False[Controls]
up = W
down = S
left = A
right = D
🔍 说明
-
每个
[Section]
表示一个配置区域。 -
每个节下有若干 “键=值” 对。
-
注释可用
#
或;
开头。 -
配置文件为纯文本,方便人类阅读与修改。
为什么使用 configparser?
特点 | 说明 |
---|---|
🧩 标准库自带 | 无需安装第三方模块 |
⚙️ 轻量易读 | 格式清晰,便于维护 |
💡 灵活可扩展 | 支持插值、默认值与多文件合并 |
🔄 双向操作 | 既能读配置,也能写配置 |
🧱 应用广泛 | 常用于应用启动配置、数据库连接、系统参数设定等 |
一、模块简介
💡 什么是 configparser
?
configparser
是 Python 标准库中的一个配置解析模块,用于读取、写入和管理 INI 格式的配置文件。
它让程序的配置参数从代码中解耦出来,方便用户自定义修改。
🔍 模块特点
特点 | 说明 |
---|---|
✅ 跨平台 | 无论 Linux、Windows 还是 macOS 均可使用 |
📦 标准库内置 | 无需安装第三方包 |
🧠 易读易写 | INI 格式语法简单直观 |
🔄 支持类型转换 | 可自动转换 int / float / bool 类型 |
🧩 支持插值 | 可在值中引用其他配置项 |
🛠️ 支持默认值、回退与自定义解析逻辑 | 适用于复杂配置环境 |
🏷️ 典型应用场景
-
系统或应用配置管理
-
数据库连接配置
-
用户偏好设置
-
多环境配置(dev / prod)
-
命令行工具的外部配置支持
二、核心类与设计原理
🎯 核心类
类名 | 说明 |
---|---|
ConfigParser |
常用解析器类,支持插值与类型转换 |
RawConfigParser |
纯文本读取,不进行插值替换 |
SafeConfigParser |
已弃用(功能由 ConfigParser 取代) |
🧩 常用方法分类总览
类别 | 方法 | 说明 |
---|---|---|
读取配置 | read() , read_file() , read_string() |
从文件或字符串读取配置 |
写入配置 | write() |
写回配置文件 |
节管理 | sections() , has_section() , add_section() , remove_section() |
管理 [section] 区块 |
选项管理 | options() , has_option() , get() , set() , remove_option() |
管理键值对 |
类型转换 | getint() , getfloat() , getboolean() |
将字符串值转为特定类型 |
默认值与回退 | fallback 参数 |
获取失败时提供默认值 |
三、ConfigParser 对象详解
🧱 初始化参数与含义
config = configparser.ConfigParser(defaults=None,dict_type=dict,allow_no_value=False,delimiters=('=', ':'),comment_prefixes=('#', ';'),inline_comment_prefixes=None,strict=True,empty_lines_in_values=True,default_section=configparser.DEFAULTSECT,interpolation=configparser.BasicInterpolation()
)
参数 | 类型 | 默认值 | 说明 |
---|---|---|---|
defaults |
dict | None |
提供默认键值对 |
dict_type |
type | dict |
指定内部存储结构 |
allow_no_value |
bool | False |
允许选项无值(仅键) |
delimiters |
tuple | ('=', ':') |
键值分隔符 |
comment_prefixes |
tuple | ('#', ';') |
注释前缀 |
strict |
bool | True |
禁止重复节名 |
interpolation |
类 | BasicInterpolation() |
插值机制控制 |
四、配置文件操作
📥 读取配置文件
import configparserconfig = configparser.ConfigParser()# 方式1:从文件路径读取
config.read('config.ini', encoding='utf-8')# 方式2:读取多个配置文件
config.read(['base.ini', 'dev.ini', 'local.ini'])# 方式3:从文件对象读取
with open('config.ini', 'r') as f:config.read_file(f)# 方式4:从字符串读取
config.read_string("""
[DEFAULT]
host = localhost
port = 8080[database]
user = admin
password = 123456
""")
方法 | 参数 | 返回 | 说明 |
---|---|---|---|
read(filenames, encoding=None) |
文件名或列表 | 成功读取的文件列表 | 批量加载文件 |
read_file(f, source=None) |
文件对象 | None |
从文件对象读取 |
read_string(string) |
配置字符串 | None |
从字符串读取 |
📤 写入配置文件
with open('output.ini', 'w', encoding='utf-8') as f:config.write(f)
📌
write()
方法自动按 INI 格式输出,保留注释与分隔符。
五、数据类型与转换
方法 | 类型 | 说明 |
---|---|---|
get() |
str | 获取字符串 |
getint() |
int | 获取整数 |
getfloat() |
float | 获取浮点数 |
getboolean() |
bool | 获取布尔值 |
🔎 布尔识别规则
-
True
:"1"
,"yes"
,"true"
,"on"
-
False
:"0"
,"no"
,"false"
,"off"
示例
config = configparser.ConfigParser()
config.read('app.ini')host = config.get('server', 'host')
port = config.getint('server', 'port')
debug = config.getboolean('server', 'debug')
timeout = config.getfloat('network', 'timeout')
六、值插值(Interpolation)
configparser
支持在配置值中引用其他键值:
config.read_string("""
[DEFAULT]
base = /opt/app
log = %(base)s/logs
data = %(base)s/data[server]
log_file = %(log)s/server.log
""")print(config.get('server', 'log_file'))
# 输出:/opt/app/logs/server.log
🧩 自定义插值器
from configparser import ConfigParser, BasicInterpolation
import osclass EnvInterpolation(BasicInterpolation):"""支持 ${VAR} 读取环境变量"""def before_get(self, parser, section, option, value, defaults):value = super().before_get(parser, section, option, value, defaults)return os.path.expandvars(value)config = ConfigParser(interpolation=EnvInterpolation())
七、默认值与回退机制
⚙️ 默认节([DEFAULT]
)
DEFAULT
节中定义的配置会被所有节继承。
[DEFAULT]
encoding = utf-8
timeout = 30[server]
host = 127.0.0.1
port = 8080
config.get('server', 'encoding') # 返回 utf-8
🧯 回退机制 fallback
value = config.get('section', 'option', fallback='default_value')
num = config.getint('section', 'count', fallback=0)
八、实战案例
import logging
from os import path
from configparser import ConfigParser# print(path.abspath(".")) # 当前目录路径
# print(path.abspath("..")) # 上一级目录路径def getpath(section,option):filepath = path.join(path.abspath(".."),"config.ini")if not path.exists(filepath):logging.error("The file is not exist")conn = ConfigParser()conn.read(filepath,encoding="utf-8")print(conn.get(section, option))
getpath("server","host")
📘 一句话总结
configparser
是 Python 世界中最优雅的 INI 文件读写利器。
它让你的程序配置“像人写的,而不是机器生成的”。