• python之ConfigParser模块


    ConfigParser翻译中文的意思是配置解析,我理解成配置文件,相当于公司开发同事写的那些java c#程序的配置文件

    1.简介

    ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容

     1 import configparser
     2 config = configparser.ConfigParser()
     3 filename='info.txt'
     4 
     5 config.read(filename, encoding="utf-8")
     6 config.add_section('host_info')#添加section,相当于字典中的key
     7 config.set('host_info','host','192.168.11.121')#添加option
     8 config.set('host_info','port','22')
     9 config.set('host_info','user','root')
    10 config.set('host_info','passwd','root11')
    11 
    12 config.add_section('cmd')
    13 config.set('cmd','dir','d:\test')
    14 config.set('cmd','file','test.py')
    15 config.set('cmd','cmd_run','mkdir')
    16 
    17 config.write(open(filename,'w')) #将添加的配置信息写到文件当中
    18 
    19 a=config.options('host_info') #host_info这个section的所有信息赋予a,一个列表
    20 d=config.options('cmd')
    21 b=config.get('host_info','host')#host_info的host的option值赋予给b
    22 c=config.get('host_info','port')
    23 #print(config.sections())
    24 print(a)
    25 print(b)
    26 print(c)
    27 print(d)
    View Code

     运行结果

    ['host', 'port', 'user', 'passwd']
    192.168.11.121
    22
    ['dir', 'file', 'cmd_run']

    获取指定节点下指定option的值
    • ConfigParserObject.get(section, option)
      返回结果是字符串类型
    • ConfigParserObject.getint(section, option)
      返回结果是int类型
    • ConfigParserObject.getboolean(section, option)
      返回结果是bool类型
    • ConfigParserObject.getfloat(section, option)
      返回结果是float类型
    检查section或option是否存在
    • ConfigParserObject.has_section(section)
    • ConfigParserObject.has_option(section, option)
      返回bool值,若存在返回True,不存在返回False
    删除section或option
    • ConfigParserObject.remove_section(section)
      若section存在,执行删除操作;
      若section不存在,则不会执行任何操作
    • ConfigParserObject.remove_option(section, option)
      若option存在,执行删除操作;
      若option不存在,则不会执行任何操作;
      若section不存在,则会报错configparser.NoSectionError: No section: XXX


    写入内容
    • ConfigParserObject.write(open(filename, 'w'))
      对configparser对象执行的一些修改操作,必须重新写回到文件才可生效



  • 相关阅读:
    委托-张子扬博客
    委托-雾中人博客
    委托基础
    C# 字典
    相机标定目的<3>
    相机标定程序详解<2>
    相机标定 <1>
    Opencv 几何变换<9>
    Opencv ROI<8>
    Opencv 通道分离合并<7>
  • 原文地址:https://www.cnblogs.com/magic-dw/p/13574326.html
Copyright © 2020-2023  润新知