zoukankan      html  css  js  c++  java
  • 配置文件操作模块,configparser

    configparser

    configparser用于处理特定格式的文件,其本质上是利用open来操作文件。

    # 注释1
    ;  注释2
     
    [section1] # 节点
    k1 = v1    # 值
    k2:v2       # 值
     
    [section2] # 节点
    k1 = v1    # 值
    指定格式

    1、获取所有节点

    1
    2
    3
    4
    5
    6
    import configparser
     
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
    ret = config.sections()
    print(ret)

    2、获取指定节点下所有的键值对

    1
    2
    3
    4
    5
    6
    import configparser
     
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
    ret = config.items('section1')
    print(ret)

    3、获取指定节点下所有的建

    1
    2
    3
    4
    5
    6
    import configparser
     
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
    ret = config.options('section1')
    print(ret)

    4、获取指定节点下指定key的值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import configparser
     
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
     
     
    v = config.get('section1', 'k1')
    # v = config.getint('section1', 'k1')
    # v = config.getfloat('section1', 'k1')
    # v = config.getboolean('section1', 'k1')
     
    print(v)

    5、检查、删除、添加节点

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import configparser
     
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
     
     
    # 检查
    has_sec = config.has_section('section1')
    print(has_sec)
     
    # 添加节点
    config.add_section("SEC_1")
    config.write(open('xxxooo', 'w'))
     
    # 删除节点
    config.remove_section("SEC_1")
    config.write(open('xxxooo', 'w'))

    6、检查、删除、设置指定组内的键值对

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import configparser
     
    config = configparser.ConfigParser()
    config.read('xxxooo', encoding='utf-8')
     
    # 检查
    has_opt = config.has_option('section1', 'k1')
    print(has_opt)
     
    # 删除
    config.remove_option('section1', 'k1')
    config.write(open('xxxooo', 'w'))
     
    # 设置
    config.set('section1', 'k10', "123")
    config.write(open('xxxooo', 'w'))
  • 相关阅读:
    IT运维监控解决方案介绍
    Apdex——衡量服务器性能的标准
    服务器监控(包括性能指标与web应用程序)
    使用厂商MIB库查找设备OID值并实施监控的方法
    华为USG6550 MIB CPU MEM
    LInux下实时网络流量监控工具nload教程
    11gR2 集群(CRS/GRID)新功能—— SCAN(Single Client Access Name)
    如何实现网卡bond
    LeetCode(31)-Factorial Trailing Zeroes
    activiti自己定义流程之整合(五):启动流程时获取自己定义表单
  • 原文地址:https://www.cnblogs.com/cp-miao/p/5617229.html
Copyright © 2011-2022 走看看