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
  • 相关阅读:
    time 模块学习
    day 14 自定义模块,常用模块 time .datetime ,time 模块
    day 13 课后作业
    day 12 课后作业
    day 11课后作业
    树状数组最值
    hdu 1059 Dividing bitset 多重背包
    XVII Open Cup named after E.V. Pankratiev. XXI Ural Championship
    最长公共子序列板/滚动 N^2
    Uva 10635
  • 原文地址:https://www.cnblogs.com/jingxindeyi/p/12945385.html
Copyright © 2011-2022 走看看