python 配置文件的使用

配置文件的使用

  • 1.设置配置文件config.ini
[uat_env]
host = http://baidu.com
  • 2.配置文件读取、新增配置分组、设置配置的key和value
#!usr/bin/env python  
# -*- coding:utf-8 _*-

'''
封装config.ini配置文件的相关方法
'''
import os
from configparser import ConfigParser


class Config():
    def __init__(self, cfg_file):
        self.cur_path = os.path.dirname(os.path.abspath(__file__))
        self.cfg_path = os.path.join(self.cur_path, cfg_file)
        self.config = ConfigParser()
        self.config.read(self.cfg_path)

    def get_value(self, section, option):
        '''
        获取配置文件中key对应的value
        :param section: 配置文件的分组
        :param option: 配置文件的分组下的key
        :return: 配置文件的分组下的value
        '''
        return self.config.get(section, option)

    def add_conf(self, section):
        '''
        向配置文件中增加分组
        :param section: 配置文件的分组
        :return: None
        '''
        self.config.add_section(section)
        self.write_conf()
        return

    def set_conf(self, seciton, option, value):
        '''
        设置配置文件中的分组的key、value
        :param seciton: 配置文件中的分组
        :param option: 配置文件中的分组的key
        :param value:  配置文件中的分组的value
        :return: None
        '''
        self.config.set(seciton, option, value)
        self.write_conf()
        return

    def write_conf(self):
        '''
        向配置文件写入内容
        :return: 
        '''
        with open(self.cfg_path, 'w+') as f:
            self.config.write(f)


if __name__ == '__main__':
    config = Config('config.ini')
    config.get_value('uat_env', 'host')
    # config.add_conf('db')
    config.set_conf('db', 'host', '1.1.1.1')

猜你喜欢

转载自blog.csdn.net/weixin_42176188/article/details/121049637