若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