使用python的ConfigParser模块方便的读取配置文件
2008-03-30 19:50
1686 查看
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. 就这么简单.
配置文件.顾名思议就是存放配置的文件.下面是个例子
[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. 就这么简单.
相关文章推荐
- Python模块之: ConfigParser 配置文件读取
- Python配置文件解析模块ConfigParser使用实例
- 【Python】配置文件解析模块ConfigParser使用实例
- python中利用ConfigParser模块读取配置文件
- Python使用自带的ConfigParser模块读写ini配置文件
- Python Configparser模块读取、写入配置文件
- Python使用自带的ConfigParser模块读写ini配置文件
- Python - ConfigParser模块读写配置文件
- Python读取配置文件:ConfigParser.NoSectionError: No section:
- python模块之ConfigParser: 用python解析配置文件
- python之ConfigParser读取配置文件
- python中用Configparser模块解析配置文件
- Python模块configparser(操作配置文件ini)
- python3配置文件模块configparser.ConfigParser
- Python模块:配置文件解析器configparser
- python中读取配置文件ConfigParser
- Python自动化测试 (二) ConfigParser模块读写配置文件
- Python模块之ConfigParser - 读写配置文件
- Python模块之ConfigParser - 读写配置文件
- python模块之ConfigParser: 用python解析配置文件[zt]