python configparser日志处理模块(ini格式)

configparser模块

import os

生成配置文件

import configparser  # 导入模块
confile = configparser.ConfigParser()  # 初始化confile对象
confile["DEFAULT"] = {
    "port": "2222",
    "user": 'liy',
    'pass': 'liy'
}   # 生成DEFAULT组
confile['path'] = {
      'log_path': "/var/log/xxx.log"
}  # 生成path组

with open(file='config.ini',mode='w',encoding='utf-8') as file:
      confile.write(file)  # 将配置组写入config.ini文件

读取配置文件

import configparser  # 导入模块
config = configparser.ConfigParser()  # 实例化对象
config.read('./config.ini')  # 读取配置文件
res = config.sections()  # 显示配置组
res = 'path' in config  # 输出path组是否在config中,在则输出True,反之则输出False
res = config['path']['log_path']  # 取出path组中的log_path配置项的值
res = config['path']  # 取出配置项,如果配置文件中有DEFAULT组,则也会显示
for item in res:  # 循环取出配置项
    print(item)

res = config.options('path')  # 和 config['path'] + for循环相同
res = config.items('path')  # 取出path下所有的选项及值,如果DEFAULT中包含该组中没有的选项也会显示
res = config.get('path','log_path')  # 取出path组下的log_path值
print(res)

修改配置文件

config = configparser.ConfigParser()
config.add_section('group_name')  # 添加组
config.remove_section('group_name')  # 删除组
config.remove_option('group_name', 'option')  # 删除指定组中的指定项
config.set('group_name', 'new_key', 'new_value')  # 设置指定组的新的项和对应的值
config.write(open(file='new.ini', mode='w'))
os.remove('config.ini')
os.rename('new.ini','config.ini')

猜你喜欢

转载自www.cnblogs.com/liy36/p/12920167.html