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

8 篇文章 0 订阅

导入包:

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

开发包:https://download.csdn.net/download/sz76211822/10736343

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值