zoukankan      html  css  js  c++  java
  • (15)-Python3之--configparser模块

    1.模块简介

      configparser模块是python用来读取配置文件的模块,置文件的格式跟windows下的ini或conf配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)。

    2.configparser函数常用方法

    read(filename) # 读取配置文件,直接读取ini文件内容
    
    sections() # 获取ini文件内所有的section,以列表形式返回
    
    options(sections) # 获取指定sections下所有options ,以列表形式返回
    
    items(sections) # 获取指定section下所有的键值对
    
    get(section, option) # 获取section中option的值,返回为string类型
    getint(section, option) # 获取section中option的值,返回为int类型
    getfloat(section, option) # 获取section中option的值,返回为float类型
    getboolean(section, option) # 获取section中option的值,返回为boolean类型

    例如:

    拥有配置文件:my_config.conf,内容如下:

    [teacher]
    name=whh 
    sex=class=python
    
    [student]
    name=xxxx
    sex=class=python
    teacher=whh
    age=17
    res=True
    weight=70.55
    hobby=["1","2","3","4"]
    
    [mobile_phone]
    os=android

    代码如下:

    import configparser
    
    # 实例化
    cp = configparser.ConfigParser()
    
    # 加载读取配置文件
    cp.read("my_config.conf",encoding="utf-8")
    
    # 获取配置文件所有的section
    sections = cp.sections()
    print(sections)
    
    # 获取配置文件下的某一个section
    section = cp.options("student")
    print(section)
    
    # 获取某一个section下的所有键值对
    items = cp.items("teacher")
    print(items)    # 列表
    
    # 获取某一个section下的某一个options具体的值
    get_str = cp.get("student","class")     # 字符串类型
    print(get_str)
    
    get_int = cp.getint("student","age")    # 整数类型
    print(get_int)
    
    get_float = cp.getfloat("student","weight")     # 浮点数类型
    print(get_float)
    
    get_boolean = cp.getboolean("student","res")    # 布尔值类型
    print(get_boolean)
    
    # 转成列表
    hobby = cp.get("student","hobby")
    print(eval(hobby))
    
    答案:
    ['teacher', 'student', 'mobile_phone']
    ['name', 'sex', 'class', 'teacher', 'age', 'res', 'weight', 'hobby']
    [('name', 'whh'), ('sex', ''), ('class', 'python')]
    python
    17
    70.55
    True
    ['1', '2', '3', '4']
  • 相关阅读:
    Spring小结
    ByteBuffer使用之道
    NIO组件Selector调用实例
    NIO组件Selector详解
    NIO机制总结
    NIO组件Selector工作机制详解(下)
    javascriptBOM_DOM
    【前端】javascript基础学习
    【前端】CSS基础学习
    【mongodb】比较符及修改器
  • 原文地址:https://www.cnblogs.com/renshengruxi/p/12916805.html
Copyright © 2011-2022 走看看