python configParser 模块

2023-05-25,,

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) 写入配置文件
9、config.get() 返回文本 config.getint()返回整数
10、config.remove_option( section, option)
11、config.remove_section( section)
案例:
import ConfigParser
import os
class ReadWriteConfFile:
currentDir=os.path.dirname(file) filepath=currentDir+os.path.sep+"inetMsgConfigure.ini"
@staticmethod
br/>filepath=currentDir+os.path.sep+"inetMsgConfigure.ini"
@staticmethod<br/def getConfigParser():
cf=ConfigParser.ConfigParser()
cf.read(ReadWriteConfFile.filepath)
return cf@staticmethod
br/>@staticmethod<br/def writeConfigParser(cf):
f=open(ReadWriteConfFile.filepath,"w"); cf.write(f)
f.close();
@staticmethod
br/>cf.write(f)
f.close();
@staticmethod<br/def getSectionValue(section,key):
cf=ReadWriteConfFile.getConfigParser()
return cf.get(section, key)@staticmethod
br/>@staticmethod<br/def addSection(section):
cf=ReadWriteConfFile.getConfigParser()
allSections=cf.sections()
if section in allSections:return
else:
cf.add_section(section)
ReadWriteConfFile.writeConfigParser(cf)
@staticmethod
br/>return
else:
cf.add_section(section)
ReadWriteConfFile.writeConfigParser(cf)
@staticmethod<br/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 模块.doc》

下载本文的Word格式文档,以方便收藏与打印。