configparser模块可方便读取.ini配置文件,支持节、键、值结构,适用于数据库、日志等设置管理。1. 创建ConfigParser对象并加载文件;2. 使用get、getint、getboolean等方法读取对应类型值;3. 通过has_section、has_option或in操作符检查节或选项存在性;4. 可动态修改配置并用set添加新内容;5. 调用write方法将更改写回文件。建议使用绝对路径避免读取错误。

Python 中使用 configparser 模块读取配置文件非常方便,尤其适用于 .ini 格式的配置文件。这类文件结构清晰,适合存储应用程序的设置信息,比如数据库连接、日志路径、API 密钥等。
configparser 支持标准的 INI 文件格式,由节(section)、键(key)和值(value)组成。例如,创建一个名为 config.ini 的文件:
[database] host = localhost port = 5432 user = admin password = secret <p>[logging] level = DEBUG file = app.log</p><p>[features] enable_cache = true max_retries = 3
使用 configparser 读取上述配置文件的基本步骤如下:
导入模块并创建 ConfigParser 对象,调用 read() 方法加载文件。
from configparser import ConfigParserconfig = ConfigParser() config.read('config.ini')
host = config.get('database', 'host') port = config.getint('database', 'port') # 自动转为整数 password = config.get('database', 'password')
cache_enabled = config.getboolean('features', 'enable_cache')
立即学习“Python免费学习笔记(深入)”;
ERMEB云盘发卡系统官方正版系统发卡系统操作简单、方便、易懂,系统微信小程序前端采用nuiapp、后端采用think PHP6,PC前端采用vue开发,使用场景:文件上传储存。适合个人/个体/中小企业使用,本系统配合微信小程序端进行使用,文件下载以及发卡商品卡密领取都需要进入小程序内获取下载码以及卡密领取,小程序内可设置积分充值以及任务获取积分,支持微信激励广告领取文件下载码以及卡密商品,可实现
0
print(host) # 输出: localhost print(port) # 输出: 5432 print(cache_enabled) # 输出: True
在读取前判断节或键是否存在,可避免 KeyError 异常。
if config.has_section('database'): if config.has_option('database', 'host'): print(config.get('database', 'host'))或者直接用 in 操作符:
if 'database' in config: if 'host' in config['database']: print(config['database']['host'])可以动态修改配置,并保存回文件。
# 修改现有值 config.set('logging', 'level', 'INFO')if not config.has_section('server'): config.add_section('server') config.set('server', 'host', '0.0.0.0') config.set('server', 'port', '8000')
with open('config.ini', 'w') as f: config.write(f)
基本上就这些。configparser 使用简单,适合中小型项目管理配置。注意读取时类型转换要用 getint、getboolean 等方法,避免手动处理出错。文件路径要确保正确,建议使用绝对路径或配合 os.path 处理相对路径。
以上就是Python 读取配置文件 configparser 使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号