Linux python3 configparser包读写ini,并解决写ini小写的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sz76211822/article/details/83616417

导入包:

import configparser
#导入 configparser包
class iniParser(configparser.ConfigParser):
    def __init__(self, defaults=None):
        configparser.ConfigParser.__init__(self, defaults=defaults)

    def optionxform(self, optionstr):
        return optionstr

class client_info(object):
    def __init__(self, file):
        self.file = file
        self.cfg = iniParser()                 #创建一个 管理对象。
        
    def optionxform(self, optionstr):
        return optionstr
    
    def cfg_load(self):
        self.cfg.read(self.file)                               #把 文件导入管理对象中,把文件内容load到内存中
 
    def cfg_dump(self):
        se_list = self.cfg.sections()                          #cfg.sections()显示文件中的所有 section
        print('==================>')
        for se in se_list:
            print(se)
            print(self.cfg.items(se))
        print('==================>')
 
    def delete_item(self, se, key):
        self.cfg.remove_option(se, key)                          #在 section 中删除一个 item
 
    def delete_section(self, se):
        self.cfg.remove_section(se)                             #删除一个 section
 
    def add_section(self, se):
        self.cfg.add_section(se)                                #添加一个 section
        
    def get_key(self, se, key):
        return self.cfg.get(se, key)                                #添加一个 section

    def set_item(self,se, key, value):
        self.cfg.set(se, key, value)                             #往 section 中 添加一个 item(一个item由key和value构成)
 
    def save(self):
        fd = open(self.file, 'w')
        self.cfg.write(fd)                                      #在内存中修改的内容写回文件中,相当于保存
        fd.close()

读取调用:

info = client_info('test.ini')
        info.cfg_load()
        strData_ReadDevID = info.get_key(strSection, strKey)
        info.save()

写操作调用:

try:
            info = client_info(strFilePath)
            info.cfg_load()
            info.set_item(strSection, strKey, strValue)
            info.save()
        except:
            pass

猜你喜欢

转载自blog.csdn.net/sz76211822/article/details/83616417
今日推荐