python ConfigParser使用

2015-1-16 杜世伟 Python

python 读写配置文件在实际应用中具有十分强大的功能,在实际的操作中也有相当简捷的操作方案,以下的文章就是对python 读写配置文件的具体方案的介绍,望你浏览完下面的文章会有所收获。

Python中有ConfigParser类,可以很方便的从配置文件中读取数据(如DB的配置,路径的配置),所以可以自己写一个函数,实现读取config配置。
config文件的写法比较简单,[section]下配置key=value,一下是例子:config.ini
配置服务器信息
[test]
ip=192.168.11.102
port=22
user=root
password=+bBVknhkmlUOcQ==

读取config.ini信息:read_config.py
#!/usr/bin/python
#encoding:utf-8
#name:read_config.py

import ConfigParser
import os

#获取config配置文件

config = ConfigParser.ConfigParser()
path = os.path.split(os.path.realpath(__file__))[0] + '/config.ini'
config.read(path)

#其中 os.path.split(os.path.realpath(__file__))[0] 得到的是当前文件模块的目录

print config.get('test','ip') # 192.168.11.102
print config.get('test','port') # 192.168.11.102

config.set("test","port","21") # 把config.ini中test段中port端口的值修改为21

python操作配置文件
常用选项:
config = ConfigParser.ConfigParser() //初始化config实例(建立一个空的数据集实例)
config.read(filename)  //通过load文件filename来初始化config实例
config.get(section, key) //获得指定section中的key的value
config.set(section, key, value)  //在指定section中,添加一对key-value键值对
config.remove_option(section, key) //删除指定section的key
config.remove_section(section)     //删除指定section
config.write(open(filename,'w'))   //保存配置
详细参考内容:http://docs.python.org/2/library/configparser.html

标签: python os ConfigParser

Powered by emlog 沪ICP备2023034538号-1