最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
python配置文件模块ConfigParser教程
时间:2016-07-23 编辑:简简单单 来源:一聚教程网
configParser 基本使用
读取配置文件
-read(filename) 直接读取文件内容
-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将内容写入配置文件。
配置文件可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
配置文件example.conf
[db]
db_host = 1.1.1.1
db_port = 3306
db_user = mysql
db_pass = sasa
[args]
aa = 1
bb = 2
[domain]
url = http://www.linuxyan.com
上面配置文件中用的是等号,也可以用冒号。
用configParser读取配置文件example.py
#!/usr/bin/python
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('example.conf')
读取所有节点
s = config.sections()
print "All sections:",s
#结果
All sections: ['db', 'args', 'domain']
读取db节点所有key
o = config.options("db")
print 'db options:', o
#结果
db options: ['db_host', 'db_port', 'db_user', 'db_pass']
读取指定的value
db_host = config.get("db", "db_host")
print db_host
#结果
1.1.1.1
读取指定类型的value(现在有get() getint() getfloat() getboolean())
db_port = config.getint("db", "port")
print db_port
#结果
3306
用configParser写入配置文件example.py
#!/usr/bin/python
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('example.conf')
#添加一个sections
config.add_section("node")
#在node中添加一个node_key = value
config.set("node","node_key","value")
config.write(open("example.conf", "w"))
#结果
[node]
node_key = value
相关文章
- spring的maven配置文件整理 04-11
- 深入分析Redis3.2.5配置文件解释 11-21
- python配置文件操作的例子 10-28
- Ubuntu下NFS网络文件系统搭建、配置和使用总结 07-25
- sublime text preference 配置文件 08-15
- fckeditor文件配置 04-25