python中configparser模块

python中的configparse模块的使用

主要用来解析一些常用的配置,比如数据配置等。

例如:有一个dbconfig.ini的文件

 1 [section_db1]
 2 db = test_db1
 3 host = 127.0.0.1
 4 port = 3319
 5 user = root
 6 password = 123456
 7 
 8 [section_db2]
 9 db = test_db2
10 host = 127.0.0.1
11 port = 3318
12 user = root
13 password = 123456
14 
15 [section_db5]
16 db = test_db5

 常用操作代码:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Eric.yue

import configparser
conf = configparser.ConfigParser()

'''
读取操作
'''
#获取section
conf.read('dbconfig.ini')
ret = conf.sections()
print ret
#[u'section_db1', u'section_db2']

#指定节点下所有的键
ret = conf.options('section_db1')
print ret #[u'db', u'host', u'port', u'user', u'password']

#获取指定的键值对
ret = conf.items('section_db1')
print ret
#[(u'db', u'test_db1'), (u'host', u'127.0.0.1'), (u'port', u'3319'), (u'user', u'root'), (u'password', u'123456')]


conf.read('dbconfig.ini') #文件路径
dbname = conf.get("section_db1","db") #获取指定section的db
print dbname
port = conf.getint("section_db1","port") #获取指定section的port

print type(port)
#<type 'int'>

#判断节点是否存在
has_sec = conf.has_section('section_db2')
print has_sec #True

# 添加节点
#conf.add_section("section_db4")
#conf.set("section_db4", "db", "test_db4")

#conf.add_section("section_db5")
#conf.set("section_db5", "db", "test_db5")
#conf.write(open('dbconfig.ini', 'w'))

#删除节点,会把对应节点下面的东西都会删除掉
conf.remove_section("section_db4")
conf.write(open('dbconfig.ini', 'w'))

'''
写入配置文件操作
'''
'''
#修改
conf.read('dbconfig.ini') #文件路径
conf.set("section_db1", "db", "test_db1") #增加指定section 的option的db
conf.set("section_db1", "port", "3319")  #增加指定section 的option的port

#增加
conf.add_section("section_db3")    #增加section
conf.set("section_db3", "db", "test_db3")
conf.set("section_db3", "host", "127.0.0.1")
conf.set("section_db3", "port", "3319")
conf.set("section_db3", "user", "root")

#最后执行才操作
conf.write(open('dbconfig.ini', 'w'))
'''

 

posted @ 2017-01-04 14:14  北京流浪儿  阅读(310)  评论(0编辑  收藏  举报