python解析模块(ConfigParser)使用方法
哑巴皇后要训夫,蛮锤军需官,李z瑞事件29g完整版
测试配置文件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如何查看网页代码
用python查看网页代码的方法:1、使用“import”导入requests包import requests2、使用requests包的get()函数通过网页...
[阅读全文]
-
-
python如何保存文本文件
python保存文本文件的方法:使用python内置的open()类可以打开文本文件,向文件里面写入数据可以用write()函数,写完之后,使用close()函...
[阅读全文]
-
python如何编写win程序
python可以编写win程序。win程序的格式是exe,下面我们就来看一下使用python编写exe程序的方法。编写好python程序后py2exe模块即可将...
[阅读全文]
-
-
-
-
-
-
网友评论