分享一个python操作.ini 文件类,该类基于configobj库,代码如下:

##!/usr/bin/python3 # -*- coding: utf-8 -*- # @descrip : ini file library that is related with project # @Time : 2021/07/14 20:40 # @Author : mftang import os import logging from configobj import ConfigObj class Op_ini_file(): def __init__(self, inifile): self.file = inifile def create_ini_file(self): if os.path.exists(self.file) == False: open(self.file, 'a ', newline='') else: filepath = os.path.abspath(self.file) logging.info("%s is exist" % filepath) def write_value(self, section, key, value): config = ConfigObj(self.file, encoding='UTF8') config[section] = {} config[section][key] = value config.write() def read_value(self,section,key): config = ConfigObj(self.file, encoding='UTF8') val = config.get(section, key) return val


写一个简单的案例测试该代码:

class Debug_configfile(object): def __init__(self): def test_inifile(self):file = "test.ini" test = Op_ini_file(file) #test.create_ini_file() test.write_value("ID-1", "id", "123124312") logging.info(test.read_value("ID-1", "id")) test.write_value("ID-2", "id", "123124312345325") logging.info(test.read_value("ID-2", "id")) if __name__ == '__main__': debug = LogTool() debug.setup_logging() testobj = Debug_configfile() testobj.test_inifile()


测试结果如下:

python的init怎么执行(Python操作.ini文件)(1)

,