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的dataframe和matrix的互换方法

实例如下所示: #-*- encoding:utf-8 -*- import pandas as pd import numpy as np df = pd.DataFrame(np...

PyTorch基本数据类型(一)

PyTorch基本数据类型(一)

PyTorch基础入门一:PyTorch基本数据类型 1)Tensor(张量) Pytorch里面处理的最基本的操作对象就是Tensor(张量),它表示的其实就是一个多维矩阵,并有矩阵相...

python 接口返回的json字符串实例

如下所示: JSON 函数 使用 JSON 函数需要导入 json 库:import json。 函数 描述 json.dumps 将 Python 对象编码成 JSON 字符串...

opencv设置采集视频分辨率方式

如下所示: #include <opencv2\opencv.hpp> #include<ctime> using namespace cv; usi...

程序员写Python时的5个坏习惯,你有几条?

很多文章都有介绍怎么写好 Python,我今天呢,相反,说说写代码时的几个坏习惯。有的习惯会让 Bug 变得隐蔽难以追踪,当然,也有的并没有错误,只是个人觉得不够优雅。 注意:示例代码在...