configparser模块是读取类ini文件使用,其有固定的读取格式如下:

  1. [section1]
  2. option11 = value11
  3. option12 = value12
  4. ....
  5. [section2]
  6. option21 = value21
  7. option22 = value22
  8. ...

假如我们有一个config.ini文件结构如下:

  1. [IP]
  2. port = 8808
  3. address = http://sdv.functest.com
  4. [password]
  5. globalMD5 = functest

通过下面的代码来分别说明configparser的增删改查

1、查询

用下面代码来实现:

  1. import configparser
  2. import os
  3.  
  4. filepath = os.path.join(os.getcwd(),'config.ini')
  5. cp = configparser.ConfigParser()
  6. cp.read(filepath)
  7. sections = cp.sections()#查询配置文件中所有section,即节点的值
  8. options = cp.options('IP')#查询某个section下所有的参数
  9. items = cp.items('IP')#查询某个section下所有的键值对
  10. get_port = cp.get('IP','port')#查询某个section下某个参数的值,若需要int或者float也可以直接使用geint或者getfloat或者getboolean
  11. get_address = cp.get('IP','address')
  12. get_globalMD5 = cp.get('password','globalMD5')
  13.  
  14. print('sections:',sections)
  15. print('options_IP:',options)
  16. print('items_IP:',items)
  17. print('port:',get_port)
  18. print('address:',get_address)
  19. print('globalMD5:',get_globalMD5)

得到的结果如下:

  1. sections: ['IP', 'password']
  2. options_IP: ['port', 'address']
  3. items_IP: [('port', ''), ('address', 'http://sdv.functest.com')]
  4. port: 8808
  5. address: http://sdv.functest.com
  6. globalMD5: functest

这里要说明下getboolean可以获取包括yes/no,on/off,true/false,1/0等值yes,on,true和1标识True,不区分大小写

另外,获取配置文件并不一定需要get,也可以有另外一种写法,如下:

  1. import configparser
  2. import os
  3.  
  4. filepath = os.path.join(os.getcwd(),'config.ini')
  5. print(filepath)
  6. cp = configparser.ConfigParser()
  7. cp.read(filepath)
  8.  
  9. #打印section
  10. for sec in cp:
  11. print(sec)
  12. #打印IP中的option
  13. for opt in cp['IP']:
  14. print(opt)
  15. #获取globalMD5的值
  16. get_globalMD5 = cp['password']['globalMD5']
  17.  
  18. print('globalMD5:',get_globalMD5)

上述代码执行结果如下:

  1. D:\PycharmProjects\untitled\MyTestProject\MyLearn\config.ini
  2. DEFAULT
  3. IP
  4. password
  5. port
  6. address
  7. globalMD5: functest

可以看到section中多了个DEFAULT,这个是默认section,和configparser.ConfigParser的参数default_section有关,后面会讲到

2、修改

修改主要用set来实现,代码如下:

  1. import configparser
  2. import os
  3.  
  4. filepath = os.path.join(os.getcwd(),'config.ini')
  5. cp = configparser.ConfigParser()
  6. cp.read(filepath)
  7.  
  8. #修改
  9. cp.set('IP','port','')#修改当前sectionoption的值,这里也可以使用cp['IP']['port'] = '9900'来写
  10. with open(filepath,'w+') as f:
  11. cp.write(f)

这个是最简单的,只要设置了对应参数的值,然后保存下即可,修改后的config.ini文件如下:

  1. [IP]
  2. port = 9900
  3. address = http://sdv.functest.com
  4.  
  5. [password]
  6. globalmd5 = functest

和查询类似,这边set也可以类似get直接写成如下:

  1. import configparser
  2. import os
  3.  
  4. filepath = os.path.join(os.getcwd(),'config.ini')
  5. print(filepath)
  6. cp = configparser.ConfigParser(default_section='password')
  7. cp.read(filepath)
  8.  
  9. get_globalMD5_1 = cp['password']['globalMD5']
  10. cp['password']['globalMD5'] = 'test'
  11. with open(filepath,'w+') as f:
  12. cp.write(f)
  13. get_globalMD5_2 = cp['password']['globalMD5']
  14.  
  15. print('globalMD5_1:',get_globalMD5_1)
  16. print('globalMD5_2:',get_globalMD5_2)

执行结果如下:

  1. globalMD5_1: functest
  2. globalMD5_2: test

3、增加

增加有两类:一是增加section,一个是增加option,都是比较简单的操作,代码实现如下:

  1. import configparser
  2. import os
  3.  
  4. filepath = os.path.join(os.getcwd(),'config.ini')
  5. cp = configparser.ConfigParser()
  6. cp.read(filepath)
  7.  
  8. #增加
  1. cp.add_section('addtest1')#增加一个section
    cp.add_section('addtest2')
    cp.set('addtest1','country','china')#若已经存在对应option则为修改,若不存在则为增加
    cp.set('addtest1','province','jiangsu')
    cp.set('addtest2','country','china')
    cp.set('addtest2','province','shandong')
    with open(filepath,'w+') as f:
    cp.write(f)

其实也很简单set既可作修改也可以做增加使用,执行后config.ini文件如下:

  1. [IP]
    port = 9900
    address = http://sdv.functest.com
  2.  
  3. [password]
    globalmd5 = functest
  4.  
  5. [addtest1]
    country = china
    province = jiangsu
  6.  
  7. [addtest2]
    country = china
    province = shandong

4、删除

删除有俩个操作,一个是删除section同时会删除section下的所有option,另外一个是删除option,代码如下:

  1. import configparser
  2. import os
  3.  
  4. filepath = os.path.join(os.getcwd(),'config.ini')
  5. cp = configparser.ConfigParser()
  6. cp.read(filepath)
  7.  
  8. #删除
  9. cp.remove_option('addtest1','province')#删除option
  10. cp.remove_section('addtest2')#删除section
  11. with open(filepath,'w+') as f:
  12. cp.write(f)

python就是这么简单,只要符合格式,操作就很简单,执行结果如下:

  1. [IP]
  2. port = 9900
  3. address = http://sdv.functest.com
  4.  
  5. [password]
  6. globalmd5 = functest
  7.  
  8. [addtest1]
  9. country = china

addtest2已经全部删除,addtest1中只剩下country这个option

5、判断配置文件中是否有对应的section或option

代码如下:

  1. import configparser
  2. import os
  3.  
  4. filepath = os.path.join(os.getcwd(),'config.ini')
  5. cp = configparser.ConfigParser()
  6. cp.read(filepath)
  7.  
  8. #判断是否存在section
  9. if cp.has_section('IP'):
  10. print('has IP section')
  11. else:
  12. print('has not IP section')
  13.  
  14. if cp.has_section('LLL'):
  15. print('has LLL section')
  16. else:
  17. print('has not LLL section')
  18.  
  19. #判断是否存在option
  20. if cp.has_option('IP','port'):
  21. print('has port option')
  22. else:
  23. print('has not port option')
  24.  
  25. if cp.has_option('IP','url'):
  26. print('has url option')
  27. else:
  28. print('has not url option')

执行结果如下:

  1. has IP section
  2. has not LLL section
  3. has port option
  4. has not url option

以上结果是符合预期的

python之读取配置文件模块configparser(一)基本操作的更多相关文章

  1. python之读取配置文件模块configparser(二)参数详解

    configparser.ConfigParser参数详解 从configparser的__ini__中可以看到有如下参数: def __init__(self, defaults=None, dic ...

  2. python之读取配置文件模块configparser(三)高级使用---非标准配置文件解析

    非标准配置文件也是经常使用的,如何使用configparser来解析? 这要从configparser本身解析结构来说,configparser包含section和option,非标准配置文件只有op ...

  3. Python之配置文件模块 ConfigParser

    写项目肯定用的到配置文件,这次学习一下python中的配置文件模块 ConfigParser 安装就不说了,pip一下即可,直接来个实例 配置文件 project.conf [db] host = ' ...

  4. python 读取配置文件ini ---ConfigParser

    Python读取ini文件需要用到 ConfigParser 模块 关于ConfigParser模块的介绍详情请参照官网解释:https://docs.python.org/2.7/library/c ...

  5. python中读取配置文件ConfigParser

    在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介 ...

  6. Python+Selenium进行UI自动化测试项目中,常用的小技巧2:读取配置文件(configparser,.ini文件)

    在自动化测试项目中,可能会碰到一些经常使用的但 很少变化的配置信息,下面就来介绍使用configparser来读取配置信息config.ini 读取的信息(config.ini)如下: [config ...

  7. python day 9: xlm模块,configparser模块,shutil模块,subprocess模块,logging模块,迭代器与生成器,反射

    目录 python day 9 1. xml模块 1.1 初识xml 1.2 遍历xml文档的指定节点 1.3 通过python手工创建xml文档 1.4 创建节点的两种方式 1.5 总结 2. co ...

  8. python基础-7.3模块 configparser logging subprocess os.system shutil

    1. configparser模块 configparser用于处理特定格式的文件,其本质上是利用open来操作文件. 继承至2版本 ConfigParser,实现了更多智能特征,实现更有可预见性,新 ...

  9. python基础知识~配置文件模块

    一 配置文件模块   import ConfigParser ->导入模块  conf = ConfigParser.ConfigParser() ->初始化类二 系统函数  conf.r ...

随机推荐

  1. c/c++再学习:C++中public、protect、private的访问权限控制

    C++中public.protect.private的访问权限控制 访问权限 一个类的public成员变量.成员函数,可以通过类的成员函数.类的实例变量进行访问 一个类的protected成员变量.成 ...

  2. Emsemble

    RM # -*- coding: utf-8 -*- """ RandomForestClassifier 예 """ import pan ...

  3. jdk1.7更新visualvm插件

    所有的插件全部更新到hithub上 https://visualvm.github.io/pluginscenters.html 然后,在根据不同的JDK版本选择不同的插件地址.更改VisualVM插 ...

  4. SparkSQL

    Spark SQL Spark SQL是Spark用来处理结构化数据的一个模块,它提供了2个编程抽象:DataFrame和DataSet,并且作为分布式SQL查询引擎的作用. Hive SQL是转换成 ...

  5. PBRT笔记(11)——光源

    自发光灯光 至今为止,人们发明了很多光源,现在被广泛使用的有: 白炽灯的钨丝很小.电流通过灯丝时,使得灯丝升温,从而使灯丝发出电磁波,其波长的分布取决于灯丝的温度.但大部分能量都被转化为热能而不是光能 ...

  6. Centos7安装zabbix-agent

    1.下载zabbix-agent wget https://mirrors.aliyun.com/zabbix/zabbix/3.4/rhel/7/x86_64/zabbix-agent-3.4.10 ...

  7. AT与ATX电源 - 1 系统状态

    ATX与AT电源比较 ATX电源普遍应用在PC中,它有两套电源,一个是正常操作使用:12V,5V,3.3V和-12V,还有一个独立的5V待机电源,所谓的待机电源就是其ON的充要条件是AC输入存在,而正 ...

  8. jquery for循环

    第一种: for(var i=0,len=$len.length; i<len; i++){//alert($len.eq(i).html());$zongshu=$zongshu+$len.e ...

  9. cf 744D

    一开始没看懂题解,想了好久(一整天)才想明白是枚举弦上点二分半径check角度,看了下clj的代码发现思路都一样就开始写了. 借鉴了一下clj的代码. 调了一个多小时. 几个注意点:看到好多 rand ...

  10. vue-router的学习

    一.路由的概述. vue-router是vue.js官方的路由插件,它和vue.js是深度集成的,适用于构建单页面.vue的单页面应用是基于路由和组件的,路由是用于设定访问路径,并将路径和组件映射起来 ...