本文实例讲述了python读写ini配置文件方法。分享给大家供大家参考。具体实现方法如下:
import configparser
import os
class readwriteconffile:
currentdir=os.path.dirname(__file__)
filepath=currentdir+os.path.sep+”inetmsgconfigure.ini”
@staticmethod
def getconfigparser():
cf=configparser.configparser()
cf.read(readwriteconffile.filepath)
return cf
@staticmethod
def writeconfigparser(cf):
f=open(readwriteconffile.filepath,”w”);
cf.write(f)
f.close();
@staticmethod
def getsectionvalue(section,key):
cf=readwriteconffile.getconfigparser()
return cf.get(section, key)
@staticmethod
def addsection(section):
cf=readwriteconffile.getconfigparser()
allsections=cf.sections()
if section in allsections:
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′)
print x
希望本文所述对大家的python程序设计有所帮助。