configparser模块 --读取配置文件
说明:
configparser模块是用来解析ini配置文件的解析器,可以包含一个或多个节,每个节可以有多个参数(键=值)。
创建配置文件:
import configparser #配置文件
config = configparser.ConfigParser()
"""生成configparser配置文件 ,字典的形式"""
"""第一种写法"""
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
"""第二种写法"""
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
"""第三种写法"""
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
"""写入后缀为.ini的文件"""
with open('example.ini', 'w') as configfile:
config.write(configfile)
读取配置文件:
# [DEFAULT]为默认节点,后面的section都可以使用它的键值
import configparser # 配置文件
config = configparser.ConfigParser()
config.read("example.ini")
## 获取所有节点
print(config.sections()) ## ['bitbucket.org', 'topsecret.server.com']
# 获取默认节点的键值
print(
config.defaults()) ## OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
## 获取默认节点的键
for item in config["DEFAULT"]:
print(item)
## 获取bitbucket.org的键,包含默认节点
print(config.options(
"bitbucket.org")) ## ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
## 输出元组,包括option的key和value
print(config.items(
'bitbucket.org')) ##[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
## 获取bitbucket.org下user的值
print(config["bitbucket.org"]["user"]) ## hg
print(config.get("bitbucket.org", "user")) ## hg
## 判断bitbucket.org节点是否存在
print('bitbucket.org' in config) ## True
## 获取option值为数字的整数
print(config.getint("topsecret.server.com", "host port")) ## 50022
删除配置文件section和option的实例(默认分组有参数时无法删除,但可以先删除下面的option,再删分组):
import configparser #配置文件
config = configparser.ConfigParser()
config.read("example.ini")
"""删除分组"""
config.remove_section("bitbucket.org")
config.write(open('example.ini', "w"))
"""删除某组下面的某个值"""
config.remove_option("topsecret.server.com","host port")
config.write(open('example.ini', "w"))
分类:
python-内置函数
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了