python configparser模块

ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用在程序员写死,可以使程序更灵活。 

注意:在python 3 中ConfigParser模块名已更名为configparser

configparser函数常用方法:

读取配置文件:

1read(filename)#读取配置文件,直接读取ini文件内容 2 3sections()#获取ini文件内所有的section,以列表形式返回['logging', 'mysql'] 4 5options(sections)#获取指定sections下所有options ,以列表形式返回['host', 'port', 'user', 'password'] 6 7items(sections)#获取指定section下所有的键值对,[('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')] 8 9get(section, option)#获取section中option的值,返回为string类型10>>>>>获取指定的section下的option 127.0.0.11112getint(section,option) 返回int类型13getfloat(section, option)  返回float类型14getboolean(section,option) 返回boolen类型

举例如下:

配置文件ini如下:

[logging]

level = 20path =server =[mysql]

host=127.0.0.1port=3306user=root

password=123456

注意,也可以使用:替换=

代码如下:

import configparserfromuntil.file_systemimport get_init_path

conf = configparser.ConfigParser()

file_path = get_init_path()print('file_path :',file_path)

conf.read(file_path)

sections = conf.sections()print('获取配置文件所有的section', sections)

options = conf.options('mysql')print('获取指定section下所有option', options)

items = conf.items('mysql')print('获取指定section下所有的键值对', items)

value = conf.get('mysql','host')print('获取指定的section下的option', type(value), value)

运行结果如下:

file_path : /Users/xxx/Desktop/xxx/xxx/xxx.ini

获取配置文件所有的section ['logging','mysql']

获取指定section下所有option ['host','port','user','password']

获取指定section下所有的键值对 [('host','127.0.0.1'), ('port','3306'), ('user','root'), ('password','123456')]

获取指定的section下的option 127.0.0.1


综合使用方法:

import configparser"""读取配置文件信息"""class ConfigParser():

    config_dic = {}

    @classmethod

    def get_config(cls, sector, item):

        value = None

        try:

            value = cls.config_dic[sector][item]

        except KeyError:

            cf = configparser.ConfigParser()

            cf.read('settings.ini', encoding='utf8')#注意setting.ini配置文件的路径value = cf.get(sector, item)

            cls.config_dic = value

        finally:

            return valueif__name__=='__main__':

    con = ConfigParser()

    res = con.get_config('logging','level')

    print(res)


参考链接:

http://blog.csdn.net/henulwj/article/details/49174355

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  •   配置文件,较正规的称呼为运行控制文件,存放程序的相关信息,甚至可以为控制命令,在程序启动时开始解析。Pytho...
    小蜗牛的成长阅读 1,799评论 0 2
  • 一、configparser介绍 configparser模块主要用于读取配置文件,导入方法:import con...
    rr1990阅读 32,262评论 0 8
  • ConfigParser 可以用来读取配置文件。是一个内置模块,不需要独立安装 简单读取配置文件示例 read(f...
    SateZheng阅读 5,653评论 0 2
  • 在工作中,常常需要把小脚本共享给其他人用。他人在使用的时候,查看修改源码不太方便。于是想到使用python中的co...
    0893051f5f11阅读 1,137评论 2 0
  • 常用模块 认识模块 什么是模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文...
    go以恒阅读 2,182评论 0 6

友情链接更多精彩内容