转载本站文章请注明,转载自: 月影鹏鹏 [http://Jacky.Aiwaly.com]
本文链接: http://jk.aiwaly.com/wp/%e8%af%bb%e5%86%99%e9%85%8d%e7%bd%ae%e6%96%87%e4%bb%b6.html
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. 就这么简单.