python解析模块(ConfigParser)使用方法
2023-09-14 08:58:52 时间
测试配置文件test.conf内容如下:
代码如下:
[first]
w = 2
v: 3
c =11-3
[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']
>>> import ConfigParser
>>> conf=ConfigParser.ConfigParser()
>>> conf.read('test.conf')
['test.conf']
>>> conf.sections()
['first', 'second']
>>> for sn in conf.sections():
...
...
['w', 'v', 'c']
['sw', 'test']
获得每个区域的属性值:
代码如下:
for sn in conf.sections():
print
sn,'-->'
for attr in
conf.options(sn):
print attr,'=',conf.get(sn,attr)
for sn in conf.sections():
输出:
代码如下:
first -->
w = 2
v = 3
c = 11-3
second -->
sw = 4
test = hello
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()
cfd=open('test2.ini','w')
conf=ConfigParser.ConfigParser()
conf.add_section('test')
conf.set('test','run','false')
conf.set('test','set',1)
conf.write(cfd)
cfd.close()
上面是向test2.ini写入配置信息。
相关文章
- python中pygame怎么安_Python中pygame安装方法图文详解
- python hashlib_Python hashlib模块实例使用详解
- python数据分析-时间序列(二)ARIMA、傅里叶、小波变换、Prophet方法2021.8.10
- Python 技巧篇-pip卸载python库实例演示,查看pip命令大全方法[通俗易懂]
- 【说站】python dump方法的序列化
- 【说站】Python threading模块的常用方法
- 【说站】Python中random模块的方法整理
- 在python中用来安装第三方库的常用工具_什么库用于安装管理Python扩展包
- python做微信回复机器人_Python自动化脚本
- python中 itertools模块的使用方法
- Python面向对象编程-魔术方法-__iter__和__next__方法(二)
- Python __call__()方法(详解版)
- Python查看模块(变量、函数、类)方法
- Python获取脚本所在目录的正确方法详解编程语言
- Python rjust()字符串右对齐方法详解
- 快速安装Python MySQL模块(python安装mysql模块)
- 提升Linux环境:升级Python(linux升级python)
- 让python的Cookie.py模块支持冒号做key的方法
- python的正则表达式re模块的常用方法
- 使用setup.py安装python包和卸载python包的方法
- python模块restful使用方法实例
- win7下搭建sublime的python开发环境的配置方法
- Python使用urllib模块的urlopen超时问题解决方法
- Python中optionParser模块的使用方法实例教程