python3 configparser 改进类

刚刚玩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"))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值