zoukankan      html  css  js  c++  java
  • 【python】python configparser模块

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

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

    configparser函数常用方法:

    读取配置文件:

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

    举例如下:

    配置文件ini如下:

    [logging]
    level = 20
    path =
    server =
    
    [mysql]
    host=127.0.0.1
    port=3306
    user=root
    password=123456

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

    代码如下:

     1 import configparser
     2 from until.file_system import get_init_path
     3 
     4 conf = configparser.ConfigParser()
     5 file_path = get_init_path()
     6 print('file_path :',file_path)
     7 conf.read(file_path)
     8 
     9 sections = conf.sections()
    10 print('获取配置文件所有的section', sections)
    11 
    12 options = conf.options('mysql')
    13 print('获取指定section下所有option', options)
    14 
    15 
    16 items = conf.items('mysql')
    17 print('获取指定section下所有的键值对', items)
    18 
    19 
    20 value = conf.get('mysql', 'host')
    21 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 <class 'str'> 127.0.0.1
  • 相关阅读:
    Git 基础
    SharePoint 2013 对象模型操作"网站设置"菜单
    SharePoint 2013 隐藏部分Ribbon菜单
    SharePoint 2013 Designer系列之数据视图筛选
    SharePoint 2013 Designer系列之数据视图
    SharePoint 2013 Designer系列之自定义列表表单
    SharePoint 2013 设置自定义布局页
    SharePoint 2013 "通知我"功能简介
    SharePoint 2013 创建web应用程序报错"This page can’t be displayed"
    SharePoint 禁用本地回环的两个方法
  • 原文地址:https://www.cnblogs.com/dhs94/p/10111693.html
Copyright © 2011-2022 走看看