[分章:代码知识]python 读取INI

本文介绍了一个Python类INI_File,用于初始化、读取和写入Ini文件,处理可能出现的不按格式存储导致的错误,并展示了如何使用和调试。重点在于处理ini文件操作中的编码问题和异常管理。

 注意

若ini内部存在不按照格式存储的数据,python的ini读取会报错。

完整代码

class INI_File(object):
    def __init__(self):
        import configparser,os,time
        self.handle = None
        self.path = None
    def Ini(self, path,encoding = 'utf-8'):
        '''Ini: Initial the config file.'''
        try:
            self.handle = configparser.ConfigParser()
            self.handle.read(path,encoding = encoding)
            self.path = path
        except Exception as e:
            print(f'Ini:{e.__str__()}')
    def Read(self, section, key):
        '''Read: Read config file.'''
        try:
            value = self.handle.get(section, key)
            return value
        except Exception as e:
            print(f'Read:{e.__str__()}')
    def Write(self, section, key, value):
        '''Write: Write to config file.'''
        try:
            if not self.handle.has_section(section):
                self.handle.add_section(section)
            self.handle.set(section, key,value)
            with open(self.path,'w') as f:
                self.handle.write(f)
        except Exception as e:
            print(f'Write:{e.__str__()}')
pass # INI_File调试程序
# import configparser,time
# cf = INI_File()
# cf.Ini('E:\Work\学习\Python\练习\串口通讯\mes_config.ini','utf-8')
# cf.Write('Info','languages','123')
# time.sleep(0.1)
# a = cf.Read('Info','languages')
# print(a)
pass

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值