configparser 是 Python 的标准库之一,用于处理配置文件,它最常用于读取和写入 INI 格式的文件,INI 文件是一种结构简单的文本文件,非常适合存储应用程序的配置信息,如数据库连接、API 密钥、功能开关等。

什么是 INI 文件?
INI 文件通常由节、键和值组成,结构如下:
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
[section]: 节,用方括号括起来,用于对配置项进行分组。key = value: 键值对,每个节下可以有多个键值对。DEFAULT: 这是一个特殊的节,它的键值对会被所有其他节继承,如果其他节没有定义某个键,则会从DEFAULT节查找。
configparser 的基本用法
1 读取配置文件
步骤:
- 导入
configparser模块。 - 创建一个
ConfigParser对象。 - 使用
read()方法读取配置文件。 - 通过
get()方法获取节中的值。
示例代码:
假设我们有一个名为 config.ini 的文件,内容如上所示。

import configparser
# 1. 创建一个 ConfigParser 对象
config = configparser.ConfigParser()
# 2. 读取配置文件
# 注意:如果文件不存在,read() 方法不会报错,而是返回一个空列表
config.read('config.ini')
# 3. 获取配置项
# --- 获取特定节的值 ---
# 如果键不存在,会抛出 KeyError
# 如果节不存在,也会抛出 KeyError
user = config['bitbucket.org']['User']
port = config['topsecret.server.com']['Port']
print(f"Bitbucket User: {user}")
print(f"Topsecret Server Port: {port}")
# --- 使用 get() 方法,可以指定默认值,避免 KeyError ---
# 这是一种更安全的方式
user_safe = config.get('bitbucket.org', 'User', fallback='default_user')
non_existent_key = config.get('topsecret.server.com', 'NonExistentKey', fallback='This is a default value')
print(f"Safe get for User: {user_safe}")
print(f"Safe get for non-existent key: {non_existent_key}")
# --- 访问 DEFAULT 节中的值 ---
# 由于 DEFAULT 的键值对会被继承,所以可以直接在任何节中获取
# 或者通过特殊节名 'DEFAULT' 来访问
interval = config['topsecret.server.com']['ServerAliveInterval']
compression = config['DEFAULT']['Compression']
print(f"Inherited ServerAliveInterval: {interval}")
print(f"DEFAULT Compression: {compression}")
2 获取不同类型的值
get() 方法默认返回字符串。configparser 还提供了 getint(), getfloat(), getboolean() 方法来获取特定类型的值,这非常有用。
# 假设 config.ini 中有如下配置
# [database]
# port = 3306
# timeout = 30.5
# enabled = true
port = config.getint('database', 'port')
timeout = config.getfloat('database', 'timeout')
enabled = config.getboolean('database', 'enabled')
print(f"Port (int): {port}")
print(f"Timeout (float): {timeout}")
print(f"Enabled (bool): {enabled}")
注意:对于布尔值,configparser 非常智能,以下字符串都会被识别为 True:
1,yes,true,on- 以下字符串会被识别为
False: 0,no,false,off
3 写入配置文件
步骤:
- 创建一个
ConfigParser对象。 - 使用
section[key] = value的方式添加或修改配置项。 - 使用
write()方法将配置写入文件(通常是先打开一个文件对象)。
示例代码:

import configparser
# 1. 创建一个 ConfigParser 对象
config = configparser.ConfigParser()
# 2. 添加节和配置项
# 如果节不存在,会自动创建
config['Settings'] = {
'debug_mode': 'True',
'log_level': 'INFO',
'max_connections': '10'
}
# 可以直接修改或添加键值对
config['Settings']['log_level'] = 'DEBUG'
# 也可以在 DEFAULT 节中添加
config['DEFAULT']['application_name'] = 'MyCoolApp'
# 3. 写入文件
# 使用 'w' 模式打开文件,会覆盖原有内容
# 注意:需要先创建文件对象
with open('new_config.ini', 'w') as configfile:
config.write(configfile)
print("new_config.ini 文件已生成。")
生成的 new_config.ini 文件内容如下:
[DEFAULT] application_name = MyCoolApp [Settings] debug_mode = True log_level = DEBUG max_connections = 10
高级用法与注意事项
1 处理不存在的节或键
直接使用 config['non_existent_section'] 会抛出 KeyError,为了避免程序中断,有几种安全的方法:
-
使用
in关键字:检查节或键是否存在。if 'my_section' in config: print("Section exists!") if 'my_key' in config['my_section']: print("Key exists in section!") -
使用
get()方法的fallback参数:这是最推荐的方式,因为它代码更简洁。# 'my_section' 或 'my_key' 不存在,返回 'default_value' value = config.get('my_section', 'my_key', fallback='default_value') -
使用
configparser对象的has_section()和has_option()方法:if config.has_section('my_section') and config.has_option('my_section', 'my_key'): value = config['my_section']['my_key']
2 删除节或键
# 删除一个键
config.remove_option('Settings', 'max_connections')
# 删除一个节
config.remove_section('Settings')
# 如果成功删除,remove_section() 返回 True
# 如果节不存在,返回 False
3 获取所有节和所有键
# 获取所有节名(包括 'DEFAULT')
all_sections = config.sections()
print(f"All sections: {all_sections}") # 输出: ['DEFAULT', 'bitbucket.org', 'topsecret.server.com']
# 获取特定节中的所有键
keys_in_section = config['topsecret.server.com'].keys()
print(f"Keys in topsecret.server.com: {list(keys_in_section)}")
4 处理多行值
INI 文件中,如果一个键的值需要跨多行,可以在行首使用一个空白字符(空格或制表符)来表示续行。
config.ini 示例:
[description] story = This is a long story that continues on the next line. It can have many lines.
Python 代码:
story = config['description']['story'] print(story) # 输出: # This is a long story that continues on the next line. # It can have many lines.
完整示例:一个配置管理器
下面是一个结合了读写、错误处理的完整示例。
import configparser
import os
class ConfigManager:
def __init__(self, filename='config.ini'):
self.filename = filename
self.config = configparser.ConfigParser()
# 设置默认值,防止文件不存在时出错
self.config['DEFAULT'] = {'log_level': 'INFO', 'debug': 'False'}
self._load_config()
def _load_config(self):
"""加载配置文件"""
if os.path.exists(self.filename):
self.config.read(self.filename)
print(f"Configuration loaded from {self.filename}")
else:
print(f"Configuration file {self.filename} not found. Using defaults.")
self._save_config() # 创建一个默认的配置文件
def _save_config(self):
"""保存配置文件"""
with open(self.filename, 'w') as configfile:
self.config.write(configfile)
print(f"Configuration saved to {self.filename}")
def get(self, section, key, fallback=None):
"""安全地获取配置值"""
return self.config.get(section, key, fallback=fallback)
def set(self, section, key, value):
"""设置配置值"""
if not self.config.has_section(section): 