刚刚玩python3, 在树霉派下有一个应用读写ini文件的 感觉configparser真不好用,重复的写入一个section或是option总是要报错,覆盖不是更好,所以自己写一个类,闲话不说,上菜,让高手们见笑了.
# coding:utf-8 import configparser import os class CMyIni: def __init__(self, sFile='cfg.ini'): self.root = os.path.dirname(os.path.realpath(__file__)) self.sFile = sFile # 创建管理对象 self.conf = configparser.ConfigParser() self.conf.read(self.fnGetRealPath()) def fnGetRealPath(self): return os.path.join(self.root, self.sFile) def fnPrintPath(self): print(self.fnGetRealPath()) # cfg.ini的路径 def writeString(self, sec, item, val): if self.conf.has_section(sec) == False: self.conf.add_section(sec) print("section append:" + sec) else: print("section already exists [%s]" % sec) # print(conf.sections()) # 往select添加key和value if self.conf.has_option(sec,item) == False: self.conf.set(sec, item, val) print("item append:"+item) else: print("item exists [%s]"% item) self.conf.remove_option(sec, item) self.conf.set(sec, item, val) # with open(self.fnGetRealPath(), "w+") as f: self.conf.write(f) def getString(self, sec, item, defVal=''): self.conf.read(self.fnGetRealPath()) if self.conf.has_option(sec, item): return str(self.conf.get(sec, item)) else: return defVal # items = conf.items('secA') # print(items) # list里面对象是元祖 if __name__ == '__main__': myIni = CMyIni('aaa.ini') myIni.writeString("auth", "user", "我的帐户") myIni.writeString("auth", "pass", "我的密码") print(myIni.getString("auth", "user")) print(myIni.getString("auth", "pass"))