python解析模块(ConfigParser)使用方法
2019/7/13 21:58:14
本文主要是介绍python解析模块(ConfigParser)使用方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
测试配置文件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解析模块(ConfigParser)使用方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础
- 2024-09-2610 种方法写出更好的 Python 代码
- 2024-09-25Python编程基础详解
- 2024-09-25Python编程入门教程
- 2024-09-25从零开始使用Python构建LLaMA 3
- 2024-09-23Python中理解和使用树形结构的简单教程
- 2024-09-23Python 编程基础入门
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战