栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 配置文件的使用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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')
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/357184.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号