python解析模块(ConfigParser)使用方法
更新时间:2013年12月10日 09:39:31 作者:
很多软件都有配置文件,今天介绍一下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如何将给定字符串中的大写英文字母按以下对应规则替换
这篇文章主要介绍了Python如何将给定字符串中的大写英文字母按以下对应规则替换,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-10-10一步真实解决AttributeError:‘Upsample‘ object has no attribute‘
这篇文章主要介绍了解决解决AttributeError: ‘Upsample‘ object has no attribute ‘recompute_scale_factor‘的问题,本文给大家介绍的非常想详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-06-06
最新评论