本文实例讲述了python实现读写ini配置文件的方法。分享给大家供大家参考,具体如下:
# -*- coding: utf-8 -*-
import configparser
import os
'''读写配置文件的类
[section]
logpath = d:\log\
imageminsize = 200
'''
class configfile:
'''构造函数:初始化'''
def __init__(self,filename):
filename = unicode(filename,'utf8')
self.flag = false
if os.path.isfile(filename):
self.filename = filename
self.cf = configparser.configparser()
self.cf.read(self.filename)
self.flag = true
'''获取节为section,键值为key的值'''
def getvalue(self,section, key):
if self.flag:
try:
result = self.cf.get(section, key)
return result
except exception,e:
print e
return ""
else:
return ""
def setvalue(self,section, key,value):
if self.flag:
try:
self.cf.set(section, key, value)
self.cf.write(open(self.filename, "w"))
except exception,e:
print e
return ""
#测试代码
configfile = os.path.join(os.getcwd(),'config.conf')
cf = configfile(configfile)
print cf.getvalue("section","logpath")
cf.setvalue("section","imageminsize","200")
希望本文所述对大家python程序设计有所帮助。
希望与广大网友互动??
点此进行留言吧!