本文目录导读:

是的,Python 解析 INI 配置文件主要使用 configparser 模块(Python 3 中重命名为小写形式,Python 2 中为 ConfigParser)。
通常我们使用 configparser.ConfigParser 类。
基本使用示例
假设有一个配置文件 config.ini:
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
Python 代码解析它:
import configparser
# 创建 ConfigParser 对象
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取所有 Section
print(config.sections()) # ['bitbucket.org', 'topsecret.server.com']
# 判断是否存在某个 Section
print('bitbucket.org' in config) # True
# 读取配置值(默认返回字符串)
host = config['bitbucket.org']['User']
print(host) # 'hg'
# 使用 get() 方法
port = config.get('topsecret.server.com', 'Port')
print(port) # '50022'
# 转换类型
port_int = config.getint('topsecret.server.com', 'Port')
print(port_int) # 50022
# 使用 getboolean() - 支持 yes/no, true/false, on/off
forward = config.getboolean('topsecret.server.com', 'ForwardX11')
print(forward) # False
常用方法
| 方法 | 说明 |
|---|---|
get(section, option) |
获取字符串值 |
getint(section, option) |
获取整数值 |
getfloat(section, option) |
获取浮点数值 |
getboolean(section, option) |
获取布尔值 |
sections() |
获取所有 section 列表 |
options(section) |
获取指定 section 的所有选项 |
items(section) |
获取 (键, 值) 对列表 |
has_section(section) |
检查 section 是否存在 |
has_option(section, option) |
检查选项是否存在 |
写入配置文件
import configparser
config = configparser.ConfigParser()
# 添加 Section 和选项
config['DEFAULT'] = {
'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'
}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
config['topsecret.server.com']['Port'] = '50022'
config['topsecret.server.com']['ForwardX11'] = 'no'
# 写入文件
with open('config.ini', 'w') as configfile:
config.write(configfile)
处理多值配置
[paths] data = /usr/share/data data = /opt/data
获取列表形式的值:
# 方法1: 自定义解析
data_paths = config.get('paths', 'data').split('\n')
# 方法2: 使用 getlist()(需要自定义)
注意事项
- 大小写敏感:Section 和 option 默认大小写敏感,可以使用
ConfigParser()的optionxform参数控制 - 默认值:
[DEFAULT]section 中的值会作为其他 section 的默认值 - 值类型:所有值默认都是字符串,需要手动转换类型
- 编码问题:如果配置文件包含中文,指定
encoding='utf-8'
config.read('config.ini', encoding='utf-8')
高级用法
带占位符的配置
[paths] root = /home/user data = %(root)s/data logs = %(root)s/logs
# 自动替换占位符
data_path = config.get('paths', 'data') # '/home/user/data'
configparser 是 Python 解析 INI 文件的标准库,功能完善、使用简单,大部分场景下无需使用第三方库。