ConfigParser模块中方法介绍#
基本的读取配置文件
- read(filename) 直接读取ini文件内容
- sections() 得到所有的section,并以列表的形式返回
- options(section) 得到该section的所有option
- items(section) 得到该section的所有键值对
- get(section,option) 得到section中option的值,返回为string类型
- getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。
基本的写入配置文件
-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。
ini格式文件#
Python ConfigParser模块解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项,比如:
db_config.ini1
2
3
4
5
6
7
8[baseconf]
host=127.0.0.1
port=3306
user=root
password=root
db_name=evaluting_sys
[concurrent]
processor=20
简单应用#
1 | #!/usr/bin/python |
上边的方式还是不够通用,可以改成类的方式写个通用模块,通过参数的方式获取更灵活。
通用模块代码如下
1 | #!/usr/bin/python |