python解析模块(ConfigParser)使用方法
2023-09-14 09:00:13 时间
测试配置文件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求逆矩阵的方法,Python 如何求矩阵的逆「建议收藏」
- pycharm打包python项目_Python怎么打包
- python实现矩阵的转置_Python实现矩阵转置的方法分析
- python判断linux中文件是否存在_Python判断文件是否存在的三种方法
- python海龟绘图画圆_Python启蒙之海龟作图「建议收藏」
- 【说站】python对象方法是什么
- 【说站】Python字典常用方法汇总
- 【说站】python常量是什么
- python输出unicode编码_Python以utf8编码读取文件
- python win32api sendmessage_Python win32api.SendMessage方法代码示例[通俗易懂]
- python type error是什么意思_Python 报错 TypeError:’DoesNotExist’对象不可调用
- 【python实操】安装软件时候选择文件安装目录模块的实现方法
- Python去除字符串中空格(删除指定字符)的3种方法
- 使用Python执行Linux命令的方法(python调用linux命令)
- python获取天气api的数据(get方法)详解编程语言
- Linux查看Python版本的有效方法(linux查看python版本)
- 让python的Cookie.py模块支持冒号做key的方法
- Python读写Excel文件方法介绍
- python处理文本文件实现生成指定格式文件的方法