`
ppju
  • 浏览: 78199 次
  • 性别: Icon_minigender_1
  • 来自: 西安
文章分类
社区版块
存档分类
最新评论

python的ConfigParser

阅读更多
ConfigParser模块是python自带的读取配置文件的模块.通过他可以方便的读取配置文件. 这篇文章简单介绍一下读取配置文件的方法.

配置文件.顾名思议就是存放配置的文件.下面是个例子
[info]
age = 21
name = chen
sex = male

其中[ ] 中的info是这段配置的名字
下面age,name都是属性

下面的代码演示了如何读取配置文件.和修改配置中变量的值



from __future__ import with_statement
import ConfigParser
config=ConfigParser.ConfigParser()
with open(''testcfg.cfg'',''rw'') as cfgfile:
    config.readfp(cfgfile)
    name=config.get(''info'',''name'')
    age=config.get(''info'',''age'')
    print name
    print age
    config.set(''info'',''sex'',''male'')
    config.set(''info'',''age'',''21'')
    age=config.get(''info'',''age'')
    print name
    print age
首先    config=ConfigParser.ConfigParser()得到一个配置config对象.下面打开一个配置文件 cfgfile. 用readfp()读取这个文件.这样配置的内容就读到config对象里面了.

接下来一个问题是如何读取值.常用的方法是get() 和getint() . get()返回文本. getint()返回整数
name=config.get(''info'',''name'')  意思就是.读取config中info段中的name变量值.

最后讲讲如何设置值.使用set(段名,变量名,值) 来设置变量.config.set(''info'',''age'',''21'') 表示把info段中age变量设置为21. 就这么简单.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics