python解析模块(ConfigParser)使用方法

yipeiwu_com5年前Python基础

测试配置文件test.conf内容如下:

复制代码 代码如下:

[first]
w = 2
v: 3
c =11-3

[second]

sw=4
test: hello

测试配置文件中有两个区域,first和second,另外故意添加一些空格、换行。

下面解析:

复制代码 代码如下:

>>> import ConfigParser
>>> conf=ConfigParser.ConfigParser()
>>> conf.read('test.conf')
['test.conf']
>>> conf.sections()   #获得所有区域
['first', 'second']
>>> for sn in conf.sections():
...     print conf.options(sn)       #打印出每个区域的所有属性
...
['w', 'v', 'c']
['sw', 'test']

获得每个区域的属性值:

复制代码 代码如下:

for sn in conf.sections():
    print sn,'-->'
    for attr in conf.options(sn):
        print attr,'=',conf.get(sn,attr)

输出:

复制代码 代码如下:

first -->
w = 2
v = 3
c = 11-3
second -->
sw = 4
test = hello

好了,以上就是基本的使用过程,下面是动态的写入配置,

复制代码 代码如下:

cfd=open('test2.ini','w')
conf=ConfigParser.ConfigParser()
conf.add_section('test')         #add a section
conf.set('test','run','false')  
conf.set('test','set',1)
conf.write(cfd)
cfd.close()

上面是向test2.ini写入配置信息。

相关文章

python生成随机红包的实例写法

假设红包金额为money,数量是num,并且红包金额money>=num*0.01 原理如下,从1~money*100的数的集合中,随机抽取num-1个数,然后对这些数进行排序,在...

python3 tkinter实现添加图片和文本

python3 tkinter实现添加图片和文本

本文在前面文章基础上介绍tkinter添加图片和文本,在这之前,我们需要安装一个图片库,叫Pillow,这个需要下载exe文件,根据下面图片下载和安装。 下载完后直接双击安装exe,默...

python 计算积分图和haar特征的实例代码

下面的代码通过积分图计算一张图片的一种haar特征的所有可能的值。初步学习图像处理并尝试写代码,如有错误,欢迎指出。 import cv2 import numpy as np im...

详解python中递归函数

函数执行流程 def foo1(b,b1=3): print("foo1 called",b,b1) def foo2(c): foo3(c) print...

pandas的qcut()方法详解

pandas的qcut()方法详解

pandas的qcut可以把一组数字按大小区间进行分区,比如 data = pd.Series([0,8,1,5,3,7,2,6,10,4,9]) 比如我要把这组数据分成两部分,一...