Python3 中 configparser 模块解析配置的用法详解
configparser 简介
configparser 是 Pyhton 标准库中用来解析配置文件的模块,并且内置方法和字典非常接近。Python2.x 中名为 ConfigParser,3.x 已更名小写,并加入了一些新功能。
配置文件的格式如下:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = Tom
[topsecret.com]
Port: 50022
ForwardX11: no
“[ ]”包含的为 section,section 下面为类似于 key - value 的配置内容;
configparser 默认支持 ‘=’ ‘:’ 两种分隔。
configparser 常用方法
初始化实例
使用 configparser 首先需要初始化实例,并读取配置文件:
>>> import configparser
>>> config = configparser.ConfigParser() # 注意大小写
>>> config.read("config.ini", encoding='utf-8') # 使用utf-8编码避免报错
获取所有 sections
>>> config.sections()
['bitbucket.org', 'topsecret.com'] # 注意会过滤掉[DEFAULT]
获取指定 section 的 keys & values
>>> config.items('topsecret.com')
[('port', '50022'), ('forwardx11', 'no')] # 注意items()返回的字符串会全变成小写
获取指定 section 的 keys
>>> config.options('topsecret.com')
['Port', 'ForwardX11']
>>> for option in config['topsecret.com']:
... print(option)
Port
ForwardX11
获取指定 key 的 value
>>> config['bitbucket.org']['User']
'Tom'
>>> config.get('bitbucket.org', 'User')
'Tom'
>>> config.getint('topsecret.com', 'Port')
50022
修改指定 key 的 value
cf=configparser.ConfigParser()
cf.read(conf_file,encoding='utf-8') #写之前,需读取文件
cf.set(section,key,value)
with open(conf_file,'w+') as f:
cf.write(f)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署