zoukankan      html  css  js  c++  java
  • configparser模块

    configparser --configparser模块中的ConfigParser类用来操作ini类型的配置文件

    ini配置文件格式

    [Section1 Name]    ;节点
    KeyName1=value1    ;参数(键值对)
    KeyName2=value2
    ...
    [Section2 Name]
    KeyName21=value21
    KeyName22=value22
    
    ;注释使用(;)
    

    基本使用

    config.ini文件:

    [Section1 Name]
    KeyName1=value1
    KeyName2=value2
    [Section2 Name]
    KeyName21=value21
    KeyName22=value22

    1、读取

    from configparser import ConfigParser
    filename = 'config.ini'
    config.read(filename)
    
    # 获取节点列表
    sections_list = config.sections()
    print('节点列表:
    %s'% sections_list)
    
    # 获取某一节点下所有的键
    optinos_list = config.options(sections_list[0])
    print('键列表:
    %s'% optinos_list)
    
    #获取某一节点下所有的键值对
    item_list = config.items(sections_list[0])
    print('%s下的所有键值对列表:
    %s'% (sections_list[0],item_list))
    
    #获取具体参数键值(某一节点下某一参数的具体值)
    val1 = config.get(sections_list[0],optinos_list[0]) 
    print('%s节点下%s的值为:
    %s'% (sections_list[0], optinos_list[0], val1))
    
    # config.getint('section',option‘)  option的值必须为整形
    # config.getfloat('section',option‘)  option的值必须为浮点型
    # config.getboolean('section',option‘)  option的值必须为布尔值
    
    结果:
    节点列表:
    ['Section1 Name', 'Section2 Name']
    键列表:
    ['keyname1', 'keyname2']
    Section1 Name下的所有键值对列表:
    [('keyname1', 'value1'), ('keyname2', 'value2')]
    Section1 Name节点下keyname1的值为:
    value1
    

    2、增删改

    #!/usr/bin/python3
    # -*- config:utf-8 -*-
    import sys,os
    from configparser import ConfigParser
    
    filename = 'config.ini'
    config = ConfigParser()
    config.read(filename)
    
    '''
    增删改
    '''
    
    # 添加一个节点Section3 Name
    config.add_section('Section3 Name')
    
    # 在节点Section3 Name下添加参数
    config.set('Section3 Name', 'keyname31', 'value21')
    
    # 判断节点Section3 Name是否存在
    if config.has_section('Section3 Name'):
        print('%s节点存在'% 'Section3 Name')
    else:
        print('%s节点不存在'% 'Section3 Name')
    
    # 判断节点Section3 Name下是否存在参数keyname31
    if config.has_option('Section3 Name', 'keyname31'):
        print('%s节点存在参数%s'% ('Section3 Name','keyname31'))
    else:
        print('%s节点不存在参数%s'% ('Section3 Name','keyname31'))
    
    # 删除Section3 Name节点下的keyname31
    config.remove_option('Section3 Name','keyname31')
    
    # 删除节点Section3 Name
    config.remove_section('Section3 Name')
    
    # 将修改点写入
    config.write(open(filename,'w'))
    
    结果:
    Section3 Name节点存在
    Section3 Name节点存在参数keyname31
  • 相关阅读:
    第十二周总结
    第十一周课程总结
    第十周第十周课程总结
    第九周课程总结&实验报告(七)
    第八周课程总结&实验报告(六)
    第七周课程总结&实验报告(五)
    第六周&java实验报告四
    第五周课程总结&试验报告(三)
    学期总结
    十四周总结
  • 原文地址:https://www.cnblogs.com/jingxindeyi/p/12945385.html
Copyright © 2011-2022 走看看