• 读取配置文件(.ini或者.conf)


    I.读取配置文件

    (1) 直接读取文件内容 : -read(filename)

    (2) 得到所有的section,并以列表的形式返回 : -sections()

    (3) 得到该section的所有option : -options(section)

    (4) 得到该section的所有键值对 : -items(section)

    (5) 得到section中option的值,返回为string类型 : -get(section,option)

    (6) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数 : -getint(section,option)

    参数说明:file_name[文件名],section[模块名],option[属性名])

    II.写入配置文件

    (1) 将config对象写入至某个 .init 格式的文件 : -write(fp)

    (2) 添加一个新的section : -add_section(section)

    (3) 对section中的option进行设置,需要调用write将内容写入配置文件 : -set( section, option, value

    (4) 删除某个 section : -remove_section(section)

    (5) 删除某个 section 下的 option : -remove_option(section, option)

    完整代码如下:

    import os
    from configparser import ConfigParser
    from com.contants import CONF_DIR # 配置文件目录
    
    conf_path = os.path.join(CONF_DIR, 'conf.ini') #  配置文件路径
    
    class MyConf(ConfigParser):
    
        def __init__(self):
            # 调用父类原来的__init__方法
            super().__init__()
            self.filename = conf_path # 配置文件路径
            self.encoding = 'utf8'
            # # 创建一个文件解析对象,设置对象的conf
            # self.conf = ConfigParser()
            # # 使用解析器对象,加载配置文件中的内容
            self.read(self.filename, self.encoding) # 继承ConfigParser方法,self本省就是一个对象
            """
            # 读取配置数据调用的方法
             # get读取出来字符串,getint读取出来是数值,getfloat读取浮点数,getboolean读取布尔值:True,False
            """
    
        #
        # def get_data(self, section, option): # 可以直接调用父类的读取配置的方法
        #     """
        #     读取配置数据
        #     :param section: 配置块
        #     :param option: 配置项
        #     :return: 配置项对应的数据
        #     """
        #     # get读取出来字符串,getint读取出来是数值,getfloat读取浮点数,getboolean读取布尔值:True,False
        #     return self.get(section,option)
    
    
        def write_data(self,section,option,value):
            """
            写入数据
            :param section: 写入配置块
            :param option: 配置项
            :param value: 配置项对应的值
            :return: None
            """
            # 写入内容
            self.set(section,option,value)
            # 保存到文件
            with open(self.filename,'w',encoding=self.encoding) as f:
                self.write(f)
    
    # 创建一个对象
    conf = MyConf()
    
    if __name__ == '__main__':
    
        conf1 = conf.get('mysql','host')
        print(conf1)

     

  • 相关阅读:
    Visual Studio LightSwitch
    Android 虚拟机与真机调试配置
    点击手机 menu 硬件按钮后的显示及处理
    Windows Phone 7 真机调试
    Android 调试
    Android 新建项目 页面
    今天我的Windows Phone 7 HTC HD7 手机 升级 NoDo 了 分享一下经验
    Activity 之间调用与参数传递
    Android widget 组件
    解决 warning: found plain 'id' attribute; did you mean the new 'android:id' name? 问题
  • 原文地址:https://www.cnblogs.com/kite123/p/13743412.html
Copyright © 2020-2023  润新知