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

[section1]
option11 = value11
option12 = value12
....
[section2]
option21 = value21
option22 = value22
...

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

[IP]
port = 8808
address = http://sdv.functest.com
[password]
globalMD5 = functest

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

1、查询

用下面代码来实现:

import configparser
import os filepath = os.path.join(os.getcwd(),'config.ini')
cp = configparser.ConfigParser()
cp.read(filepath)
sections = cp.sections()#查询配置文件中所有section,即节点的值
options = cp.options('IP')#查询某个section下所有的参数
items = cp.items('IP')#查询某个section下所有的键值对
get_port = cp.get('IP','port')#查询某个section下某个参数的值,若需要int或者float也可以直接使用geint或者getfloat或者getboolean
get_address = cp.get('IP','address')
get_globalMD5 = cp.get('password','globalMD5') print('sections:',sections)
print('options_IP:',options)
print('items_IP:',items)
print('port:',get_port)
print('address:',get_address)
print('globalMD5:',get_globalMD5)

得到的结果如下:

sections: ['IP', 'password']
options_IP: ['port', 'address']
items_IP: [('port', ''), ('address', 'http://sdv.functest.com')]
port: 8808
address: http://sdv.functest.com
globalMD5: functest

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

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

import configparser
import os filepath = os.path.join(os.getcwd(),'config.ini')
print(filepath)
cp = configparser.ConfigParser()
cp.read(filepath) #打印section
for sec in cp:
print(sec)
#打印IP中的option
for opt in cp['IP']:
print(opt)
#获取globalMD5的值
get_globalMD5 = cp['password']['globalMD5'] print('globalMD5:',get_globalMD5)

上述代码执行结果如下:

D:\PycharmProjects\untitled\MyTestProject\MyLearn\config.ini
DEFAULT
IP
password
port
address
globalMD5: functest

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

2、修改

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

import configparser
import os filepath = os.path.join(os.getcwd(),'config.ini')
cp = configparser.ConfigParser()
cp.read(filepath) #修改
cp.set('IP','port','')#修改当前section中option的值,这里也可以使用cp['IP']['port'] = '9900'来写
with open(filepath,'w+') as f:
cp.write(f)

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

[IP]
port = 9900
address = http://sdv.functest.com [password]
globalmd5 = functest

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

import configparser
import os filepath = os.path.join(os.getcwd(),'config.ini')
print(filepath)
cp = configparser.ConfigParser(default_section='password')
cp.read(filepath) get_globalMD5_1 = cp['password']['globalMD5']
cp['password']['globalMD5'] = 'test'
with open(filepath,'w+') as f:
cp.write(f)
get_globalMD5_2 = cp['password']['globalMD5'] print('globalMD5_1:',get_globalMD5_1)
print('globalMD5_2:',get_globalMD5_2)

执行结果如下:

globalMD5_1: functest
globalMD5_2: test

3、增加

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

import configparser
import os filepath = os.path.join(os.getcwd(),'config.ini')
cp = configparser.ConfigParser()
cp.read(filepath) #增加
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文件如下:

[IP]
port = 9900
address = http://sdv.functest.com [password]
globalmd5 = functest [addtest1]
country = china
province = jiangsu [addtest2]
country = china
province = shandong

4、删除

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

import configparser
import os filepath = os.path.join(os.getcwd(),'config.ini')
cp = configparser.ConfigParser()
cp.read(filepath) #删除
cp.remove_option('addtest1','province')#删除option
cp.remove_section('addtest2')#删除section
with open(filepath,'w+') as f:
cp.write(f)

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

[IP]
port = 9900
address = http://sdv.functest.com [password]
globalmd5 = functest [addtest1]
country = china

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

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

代码如下:

import configparser
import os filepath = os.path.join(os.getcwd(),'config.ini')
cp = configparser.ConfigParser()
cp.read(filepath) #判断是否存在section
if cp.has_section('IP'):
print('has IP section')
else:
print('has not IP section') if cp.has_section('LLL'):
print('has LLL section')
else:
print('has not LLL section') #判断是否存在option
if cp.has_option('IP','port'):
print('has port option')
else:
print('has not port option') if cp.has_option('IP','url'):
print('has url option')
else:
print('has not url option')

执行结果如下:

has IP section
has not LLL section
has port option
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. docker 安装kafka

    1.下载镜像这里使用了wurstmeister/kafka和wurstmeister/zookeeper这两个版本的镜像 docker pull wurstmeister/zookeeperdocke ...

  2. CentOs查看某个字符串在某个目录下的行数

    如果你想在当前目录下 查找"hello,world!"字符串,可以这样: grep -rn "hello,world!" ./ ./ : 表示路径为当前目录. ...

  3. django framework相关的错误信息

    错误信息1: 报错信息: TypeError: In order to allow non-dict objects to be serialized set the safe parameter t ...

  4. CheckedTextView文字不居中的问题

    问题:CheckedTextView设置了android:gravity="center",但是不居中 解决方法:添加属性android:textAlignment="c ...

  5. 动态规划——Palindrome Partitioning II

    Palindrome Partitioning II 这个题意思挺好理解,提供一个字符串s,将s分割成多个子串,这些字串都是回文,要求输出分割的最小次数. Example:Input: "a ...

  6. 关于阿里ICON矢量图(SVG)上传问题.

    注意点: 1. 存储为svg格式(建议使用存储为svg,不要使用导出为svg)2. 图像位置:链接(注意哦,不要点嵌入和保留编辑功能)---确定3. AI里面选中图形,点对象-路径-轮廓化描边 软件编 ...

  7. CentOS7更换国内源

    前言 CentOS 有个很方便的软件安装工具yum,但是默认安装完CentOS,系统里使用的是国外的CentOS更新源,这就造成了我们使用默认更新源安装或者更新软件时速度很慢的问题,甚至更新失败. 为 ...

  8. python中的矩阵、多维数组

    2. 创建一般的多维数组 import numpy as np a = np.array([1,2,3], dtype=int)  # 创建1*3维数组   array([1,2,3]) type(a ...

  9. NOIP-螺旋矩阵

    题目描述 一个 n 行 n 列的螺旋矩阵可由如下方法生成: 从矩阵的左上角(第 1 行第 1 列)出发,初始时向右移动:如果前方是未曾经过的格子,则继续前进,否则右转:重复上述操作直至经过矩阵中所有格 ...

  10. Java for Android 第二周课上实验一

    (一)命令行下程序开发 (二)IDEA下程序开发调试 Mac OS系统下使用的IDEA为 Netbeans (三)测试题我的学号后两位为10 使用简单的PHP小程序得我的题目为2:实现简单四则运算(能 ...