码迷,mamicode.com
首页 > 编程语言 > 详细

python configParser 模块

时间:2018-06-27 12:16:34      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:文件   def   os.path   write   val   gets   etc   序列   config   

configParser 模块用于操作配置文件
配置文件(INI文件)由节(section)、键、值组成
1、config=ConfigParser.ConfigParser() 创建ConfigParser实例
2、config.sections() 返回配置文件中节序列
3、config.options(section) 返回某个项目中的所有键的序列
4、config.get(section,option) 返回section节中,option的键值
5、config.add_section(str) 添加一个配置文件节点(str)
6、config.set(section,option,val) 设置section节点中,键名为option的值(val)
7、config.read(filename) 读取配置文件
8、config.write(obj_file) 写入配置文件

案例:
import ConfigParser
import os
class ReadWriteConfFile:
currentDir=os.path.dirname(file) @staticmethod
br/>filepath=currentDir+os.path.sep+"inetMsgConfigure.ini"
@staticmethod
def getConfigParser():
cf=ConfigParser.ConfigParser()
cf.read(ReadWriteConfFile.filepath)
return cf
br/>@staticmethod
def writeConfigParser(cf):
f=open(ReadWriteConfFile.filepath,"w");
br/>cf.write(f)
f.close();
@staticmethod
def getSectionValue(section,key):
cf=ReadWriteConfFile.getConfigParser()
return cf.get(section, key)
br/>@staticmethod
def addSection(section):
cf=ReadWriteConfFile.getConfigParser()
allSections=cf.sections()
if section in allSections:
br/>return
else:
cf.add_section(section)
ReadWriteConfFile.writeConfigParser(cf)
@staticmethod
def setSectionValue(section,key,value):
cf=ReadWriteConfFile.getConfigParser()
cf.set(section, key, value)
ReadWriteConfFile.writeConfigParser(cf)
if name == ‘main‘:
ReadWriteConfFile.addSection( ‘messages‘)
ReadWriteConfFile.setSectionValue( ‘messages‘,‘name‘,‘sophia‘)
x=ReadWriteConfFile.getSectionValue( ‘messages‘,‘1000‘)

python configParser 模块

标签:文件   def   os.path   write   val   gets   etc   序列   config   

原文地址:http://blog.51cto.com/weadyweady/2133117

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!