Python 标准库:configparser——配置文件解析
文章目录
模块介绍
configparser 是 Python 标准库中的一个模块,用于读取、解析和写入 .ini 格式的配置文件。.ini 文件通常采用键值对的形式来组织配置信息,并将这些配置信息分组到不同的节(sections)中。这个模块提供了简单的接口来管理应用程序的配置,特别适用于小型或中型项目中的配置文件管理。
configparser 模块支持读取、修改和创建新的配置文件,且能方便地进行节的增删操作。它的行为类似于 Windows 平台上传统的 .ini 配置文件格式,但也可以跨平台使用,适用于 Linux 和 macOS 等其他操作系统。
使用场景
主要类
类名 | 描述 |
---|---|
ConfigParser | 这是 configparser 模块的核心类,负责读取、修改、删除 .ini 配置文件中的数据。 |
主要方法
函数 | 描述 |
---|---|
ConfigParser() | 创建一个 ConfigParser 对象,用于读取、写入和修改配置文件。 |
read(filenames) | 读取一个或多个配置文件。文件可以是绝对路径或相对路径。 |
get(section, option) | 获取指定节(section)中的指定选项(option)的值。返回字符串类型。 |
getint(section, option) | 获取指定节中指定选项的值,并将其转换为整数类型。 |
getfloat(section, option) | 获取指定节中指定选项的值,并将其转换为浮动类型。 |
getboolean(section, option) | 获取指定节中指定选项的值,并将其转换为布尔值。 |
set(section, option, value) | 设置指定节中指定选项的值。 |
add_section(section) | 向配置文件中添加一个新节(section)。 |
remove_section(section) | 删除指定的节。 |
remove_option(section, option) | 删除指定节中的指定选项。 |
write(file) | 将当前的配置写入到文件对象中。 |
sections() | 返回所有节的名称列表。 |
options(section) | 返回指定节中的所有选项名。 |
items(section) | 返回指定节中的所有选项和值,以列表的形式返回。 |
has_section(section) | 检查是否存在指定的节 |
has_option(section, option) | 检查指定节是否包含指定的选项 |
read_file(file) | 从文件对象中读取配置(与 read() 类似,但接受一个文件对象而非文件名) |
read_dict(dictionary) | 从字典读取配置 |
有如下配置文件(config.ini):
[general]
version = 1.0
author = John Doe
[settings]
max_connections = 100
timeout = 30
# timeout = 20
[advanced]
enabled = true
new_feature = Enabled
– ConfigParser()
创建一个 ConfigParser 对象。
import configparser
# 创建 ConfigParser 对象
config = configparser.ConfigParser()
– read(filenames)
读取一个或多个配置文件。
import configparser
# 创建 ConfigParser 对象
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
– get(section, option)
获取指定节和选项的值。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取 'general' 节下 'version' 选项的值
version = config.get('general', 'version')
print(f"Version: {version}")
– getint(section, option)
获取指定节中指定选项的值,并将其转换为整数类型。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取 'database' 节下 'port' 选项的值,并转换为整数
timeout = config.getint('settings', 'timeout')
print(f"timeout: {timeout}")
– getfloat(section, option)
获取指定节中指定选项的值,并将其转换为浮动类型。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取 'settings' 节下 'timeout' 选项的值,并转换为浮动类型
timeout = config.getfloat('settings', 'timeout')
print(f"Timeout: {timeout}")
– getboolean(section, option)
获取指定节中指定选项的值,并将其转换为布尔类型。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取 'advanced' 节下 'enabled' 选项的值,并转换为布尔值
enabled = config.getboolean('advanced', 'enabled')
print(f"Advanced features enabled: {enabled}")
– set(section, option, value)
设置指定节中指定选项的值。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 设置 'general' 节下 'version' 选项的值
config.set('general', 'version', '2.0')
# 将更新后的内容写回配置文件
with open('config.ini', 'w') as configfile:
config.write(configfile)
print(config.get('general', 'version'))
– add_section(section)
添加新的节(section)。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 如果没有 'new_section' 节,则添加
if not config.has_section('new_section'):
config.add_section('new_section')
# 将更新后的内容写回配置文件
with open('config.ini', 'w') as configfile:
config.write(configfile)
– remove_section(section)
删除指定的节。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 删除 'new_section' 节
config.remove_section('new_section')
# 将更新后的内容写回配置文件
with open('config.ini', 'w') as configfile:
config.write(configfile)
– remove_option(section, option)
删除指定节中的指定选项。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 删除 'general' 节下的 'version' 选项
config.remove_option('general', 'version')
# 将更新后的内容写回配置文件
with open('config.ini', 'w') as configfile:
config.write(configfile)
– write(file)
将当前的配置写入到文件对象中。
import configparser
config = configparser.ConfigParser()
# 将配置写回到文件
with open('config.ini', 'w') as configfile:
config.write(configfile)
– sections()
返回所有节的名称列表。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取所有节的名称
sections = config.sections()
print(f"Sections: {sections}")
– options(section)
返回指定节中的所有选项名。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取 'general' 节中的所有选项名
options = config.options('general')
print(f"Options in 'general' section: {options}")
– items(section)
返回指定节中的所有选项和值,结果为列表形式。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取 'general' 节中的所有选项和值
items = config.items('general')
print(f"Items in 'general' section: {items}")
– has_section(section)
检查是否存在指定的节。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 检查是否存在 'general' 节
if config.has_section('general'):
print("'general' section exists.")
else:
print("'general' section does not exist.")
– has_option(section, option)
检查指定节是否包含指定的选项。
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 检查 'general' 节下是否存在 'version' 选项
if config.has_option('general', 'version'):
print("'version' option exists in 'general' section.")
else:
print("'version' option does not exist in 'general' section.")
– read_file(file)
从文件对象中读取配置(与 read() 类似,但接受一个文件对象而非文件名)。
import configparser
config = configparser.ConfigParser()
with open('config.ini', 'r') as f:
config.read_file(f)
– read_dict(dictionary)
从字典读取配置。
import configparser
# 创建 ConfigParser 对象
config = configparser.ConfigParser()
# 定义一个字典,包含配置内容
config_dict = {
'General': {
'name': 'Alice',
'age': '25'
},
'Settings': {
'theme': 'dark',
'language': 'English'
}
}
# 使用 read_dict() 方法加载字典数据
config.read_dict(config_dict)
# 显示加载后的配置内容
print("加载后的配置内容:")
for section in config.sections():
print(f"[{section}]")
for option in config.options(section):
print(f"{option} = {config.get(section, option)}")
注意事项
节名和选项名的大小写:
文件读写模式:
类型转换:
处理缺少的节或选项:
默认值:
文件格式注意:
总结
configparser 模块为 Python 提供了简洁而强大的配置文件管理功能,特别适合管理 .ini 格式的配置文件。它支持读取、修改和写入配置文件中的节、选项和值,且能处理类型转换、缺省值、节和选项的增删等常见需求。该模块是跨平台的,适用于各种操作系统。
作者:骑个小蜗牛