Python - configparser模块:用于配置文件
2022-03-31 15:59 起个昵称 阅读(44) 评论(0) 编辑 收藏 举报支持多种格式的配置文件,如ini,yaml,xml....
ini是按需读取,yaml是一次性读取
这里以.ini为例
ini配置文件格式
格式 [section] option=value option=value [section] option=value option=value option=value 示例 [database] user=sa password=123abc [log] name=log_name level=INFO
学习笔记:读取、新增、修改、保存
1 from configparser import ConfigParser 2 3 # 1. 实例化 4 conf = ConfigParser() 5 6 # 2. 读取配置文件:read() 7 conf.read('config.ini', encoding='utf-8') # 注意配置文件的路径 8 9 # 3. 读取某一项配置:get() 10 value = conf.get('log', 'file_ok') 11 print(type(value)) # <class 'str'> 12 value = conf.getboolean('log', 'file_ok') 13 print(type(value)) # <class 'bool'> 14 value = conf.get('log', 'size') 15 print(type(value)) # <class 'str'> 16 value = conf.getint('log', 'size') 17 print(type(value)) # <class 'int'> 18 19 # 4.1 读取配置文件所有sections 20 print(conf.sections()) # ['database', 'log'] 21 # 4.2 读取配置文件指定section的所有options 22 print(conf.options('log')) # ['name', 'level', 'file_ok', 'size'] 23 24 # 5.1 新增section 25 conf.add_section('section') 26 # 5.2 存在option,重写value;不存在,则新增 27 conf.set('section', 'name', 'new_value') 28 29 # 6. 修改配置项:写入内存set() 30 conf.set('log', 'name', 'new_value') # 只改变内存,不改变文件 31 32 # 7. 保存到文件 write() 33 conf.write(open('config.ini', 'w', encoding='utf-8')) # 执行此行就是把上面的修改重写到原来的配置文件中
封装
1 import os 2 from configparser import ConfigParser 3 4 class HandleConfig(ConfigParser): 5 6 def __init__(self, file_path): 7 super().__init__() 8 self.read(file_path, encoding='utf-8') 9 10 file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini') 11 conf = HandleConfig(file_path)
调用
myConfig是HandleConfig()类的文件名,直接引入类的实例化,就不需要每次调用都实例化一次了
1 from myConfig import conf 2 3 print(conf.get('log', 'level')) # INFO
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!