首页 > 编程语言 > 详细

python 提供INI配置文件的操作 ConfigParser

时间:2014-03-03 18:55:50      阅读:564      评论:0      收藏:0      [点我收藏+]

原文地址:http://www.cnblogs.com/pumaboyd/archive/2008/08/11/1265416.html

红色的为标注信息

+++++++++++++++++引用+++++++++++++++++++++

>PY提供INI配置文件的操作


关于配置文件,很直观的感觉就是XML文件。对于XML文件的使用大家还是很喜欢的。但有时候只是简单的一个程序,实现一个简单的name:value关系。用XML文件就没这个必要。这种要求很符合MS的INI文件格式。所以这里主要介绍一下对INI文件的操作方式,而且最近写的第一个PY应用程序也是使用了INI
什么是INI  文件
PY所支持的INI文件还是和Windows系统所定义有不同,它不但支持name=value的形式,还支持name:value的形式

>PY对INI配置文件读取提供的类支持


PY的ConfigParser Module中定义了3个类对INI文件进行操作。分别是RawConfigParser、ConfigParser、SafeConfigParser
RawCnfigParser是最基础的INI文件读取类
ConfigParser、SafeConfigParser支持对$(value)s变量的支持。

>RawConfigParser类的使用方法 (建议使用)


int文件

[weburl]
urlname
=http://pumaboyd.cnblogs.com


Test.py文件

bubuko.com,布布扣
import ConfigParser, os
from __future__ import with_statement
cfg 
= ConfigParser.RawConfigParser()
with open(
"app.ini") as fobj
    cfg.readfp( fobj)
print cfg.get("weburl","urlname"
bubuko.com,布布扣

 可以查看一下help(cfg.readfp)

readfp是读取一个 file object 类似于 something.readlines() 的对象。

使用with用法,将会节省很多内存,这里比较赞同。

>ConfigParser类的使用方法


Configration类是从RawConfigParser扩展过来的,可以支持$()s变量。
对RawConfigParserd的get(),items()进行了扩展

 

int文件

[DEFAULT]
val
=pumaboyd
[weburl]
name
=%(val)s 

 

Test.py文件

bubuko.com,布布扣
bubuko.com,布布扣
import ConfigParser, os
from __future__ import with_statement
cfg 
= ConfigParser.ConfigParser()
with open(
"app.ini") as fobj
    cfg.readfp( fobj)
print cfg.defaults()
print cfg.get("weburl","name"
bubuko.com,布布扣
bubuko.com,布布扣

 

可以看到cfg.get("weburl","name") 输入的pumaboyd。如果这里采用的是RawConfigParser,你将看到输出的是%(val)s。
这里需要注意的一个地方就是DEFAULT这个默认节点。只能通过cfg.defaults()读取到。cfg.sections()是不包含DEFAULT这个节点的。

>SafeConfigParser类的使用方法


是从ConfigParser继承过来,其实是对RawConfigParser进行了扩展,可以支持$()s变量

int文件

[DEFAULT]
val
=pumaboyd
[weburl]
name
=abcd 

 

Test.py文件

bubuko.com,布布扣
bubuko.com,布布扣
import ConfigParser, os
from __future__ import with_statement
cfg 
= ConfigParser.SaftConfigParser()
with open(
"app.ini") as fobj
    cfg.readfp( fobj)
cfg.set(
"weburl","name","&(val)s")
print cfg.get("weburl","name")
bubuko.com,布布扣
bubuko.com,布布扣


你将看到输入结果是pumaboyd。如果采用的RawConfigParser,你就看到输出的是%()s

>如何修改INI文件


RawConfigParser、SafeConfigParser、ConfigParser中的SET、Remove等方法都只是对ConfigParser对象的修改,并没有真正的保存到INI文件中。所以,需要通过Write方法(3个类中都有这个方法),将修改写回INI文件中。

ini文件

 

[weburl]
name
=abcd 

 

Test.py文件

bubuko.com,布布扣
bubuko.com,布布扣
import ConfigParser, os
from __future__ import with_statement
cfg 
= ConfigParser.ConfigParser()
with open(
"app.ini") as fobj
    cfg.readfp( fobj)
cfg.set(
"weburl","name","pumaboyd"

with open(
"app.ini","w") as fwobj
    cfg.write(fwobj) 
bubuko.com,布布扣
bubuko.com,布布扣

python 提供INI配置文件的操作 ConfigParser,布布扣,bubuko.com

python 提供INI配置文件的操作 ConfigParser

原文:http://www.cnblogs.com/spaceship9/p/3577714.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!