代码改变世界

Python - configparser模块:用于配置文件

2022-03-31 15:59  起个昵称  阅读(34)  评论(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