#!/bin/env python#-*- coding:utf-8 -*-from ConfigParser import ConfigParserimport jsondef getConfigObject(filename): """获得配置文件对象 """ _config_ = ConfigParser() _config_.read(filename) return _config_def getConfigJson(filename, sections): """返回对应sections全部的options信息(键和值) """ _config_ = getConfigObject(filename) return json.dumps(dict(_config_.items(sections)),ensure_ascii=False)def setConfigValue(filename, sections, keys, value): """设置指定section中option值 """ _config_ = getConfigObject(filename) _config_.set(sections, keys, value) _config_.write(open(filename, "w"))def getConfigValue(filename, sections, keys): """读取指定section的option值 """ _config_ = getConfigObject(filename) return _config_.get(sections, keys)def getSectionsList(filename): """读取全部的sections信息 """ _config_ = getConfigObject(filename) return _config_.sections()def getSectionsKeys(filename,sections): """获得指定的sections中全部的options键 """ _config_ = getConfigObject(filename) return _config_.options(sections)if __name__ == "__main__": filename = "config.ini" sections = "control" print getConfigJson(filename, sections) print getConfigValue(filename, sections, "left") setConfigValue(filename, sections, "left","左面,在左面") print getConfigValue(filename, sections, "left") print getSectionsList(filename) print getSectionsKeys(filename, sections)
config.ini 文件内容
[control]
front = 向前,在前面back = 向后left = 左面,在左面right = 向右stop = 停止[weather]select = [0.5] + range(1,25)interval = 0.5