python读取ini配置的类封装代码实例


Posted in Python onJanuary 08, 2020

这篇文章主要介绍了python读取ini配置的类封装代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

此为基础封装,未考虑过多异常处理

# coding:utf-8
import configparser
import os

class IniCfg():
  def __init__(self):
    self.conf = configparser.ConfigParser()
    self.cfgpath = ''

  def checkSection(self, section):
    try:
      self.conf.items(section)
    except Exception:
      print(">> 无此section,请核对[%s]" % section)
      return None
    return True

  # 读取ini,并获取所有的section名
  def readSectionItems(self, cfgpath):
    if not os.path.isfile(cfgpath):
      print(">> 无此文件,请核对路径[%s]" % cfgpath)
      return None
    self.cfgpath = cfgpath
    self.conf.read(cfgpath, encoding="utf-8")
    return self.conf.sections()

  # 读取一个section,list里面对象是元祖
  def readOneSection(self, section):
    try:
      item = self.conf.items(section)
    except Exception:
      print(">> 无此section,请核对[%s]" % section)
      return None
    return item

  # 读取一个section到字典中
  def prettySecToDic(self, section):
    if not self.checkSection(section):
      return None
    res = {}
    for key, val in self.conf.items(section):
      res[key] = val
    return res

  # 读取所有section到字典中
  def prettySecsToDic(self):
    res_1 = {}
    res_2 = {}
    sections = self.conf.sections()
    for sec in sections:
      for key, val in self.conf.items(sec):
        res_2[key] = val
      res_1[sec] = res_2.copy()
      res_2.clear()
    return res_1

  # 删除一个 section中的一个item(以键值KEY为标识)
  def removeItem(self, section, key):
    if not self.checkSection(section):
      return
    self.conf.remove_option(section, key)

  # 删除整个section这一项
  def removeSection(self, section):
    if not self.checkSection(section):
      return
    self.conf.remove_section(section)

  # 添加一个section
  def addSection(self, section):
    self.conf.add_section(section)

  # 往section添加key和value
  def addItem(self, section, key, value):
    if not self.checkSection(section):
      return
    self.conf.set(section, key, value)

  # 执行write写入, remove和set方法并没有真正的修改ini文件内容,只有当执行conf.write()方法的时候,才会修改ini文件内容
  def actionOperate(self, mode):
    if mode == 'r+':
      conf.write(open(self.cfgpath, "r+", encoding="utf-8"))  # 修改模式
    elif mode == 'w':
      conf.write(open(self.cfgpath, "w"))           # 删除原文件重新写入
    elif mode == 'a':
      conf.write(open(self.cfgpath, "a"))           # 追加模式写入

cfgpath = r'C:\Users\SXF\Desktop\config.ini'

inicfg = IniCfg()
sections = inicfg.readSectionItems(cfgpath)
print(sections)
content = inicfg.readOneSection('chaoji')
print(content)
dic = inicfg.prettySecToDic('chaoji')
print(dic)
dic = inicfg.prettySecsToDic()
print(dic)
inicfg.addSection('chaoji22')

content = inicfg.readOneSection('chaoji')
print(content)

测试ini

[chaoji]
chaoji_username = 123
chaoji_password = 456
[my]
soft_id     = 789
sleeptime     = asd
cnt_count     = zxc

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python 中文乱码问题深入分析
Mar 13 Python
用Python的线程来解决生产者消费问题的示例
Apr 02 Python
深入解析Python编程中super关键字的用法
Jun 24 Python
python爬取哈尔滨天气信息
Jul 14 Python
Python 使用类写装饰器的小技巧
Sep 30 Python
python实现词法分析器
Jan 31 Python
PyQt5根据控件Id获取控件对象的方法
Jun 25 Python
Pytorch中的variable, tensor与numpy相互转化的方法
Oct 10 Python
python网络编程socket实现服务端、客户端操作详解
Mar 24 Python
Lombok插件安装(IDEA)及配置jar包使用详解
Nov 04 Python
python空元组在all中返回结果详解
Dec 15 Python
python程序实现BTC(比特币)挖矿的完整代码
Jan 20 Python
Python Des加密解密如何实现软件注册码机器码
Jan 08 #Python
Pytorch技巧:DataLoader的collate_fn参数使用详解
Jan 08 #Python
Pytorch DataLoader 变长数据处理方式
Jan 08 #Python
pytorch实现用CNN和LSTM对文本进行分类方式
Jan 08 #Python
使用pytorch和torchtext进行文本分类的实例
Jan 08 #Python
python爬虫爬取监控教务系统的思路详解
Jan 08 #Python
Pytorch实现基于CharRNN的文本分类与生成示例
Jan 08 #Python
You might like
深入解析yii权限分级式访问控制的实现(非RBAC法)
2013/06/13 PHP
PHP中include/require/include_once/require_once使用心得
2016/08/28 PHP
php执行多个存储过程的方法【基于thinkPHP】
2016/11/08 PHP
PHP 传输会话curl函数的实例详解
2017/09/12 PHP
Laravel学习教程之View模块详解
2017/09/18 PHP
PHP Post获取不到非表单数据的问题解决办法
2018/02/27 PHP
别了 JavaScript中的isXX系列
2012/08/01 Javascript
js模仿jquery的写法示例代码
2013/06/16 Javascript
js函数返回多个返回值的示例代码
2013/11/05 Javascript
Mac/Windows下如何安装Node.js
2013/11/22 Javascript
两个数组去重的JS代码
2013/12/04 Javascript
jQuery 中DOM 操作详解
2015/01/13 Javascript
JS中的Replace方法使用经验分享
2015/05/20 Javascript
深入浅析JSON.parse()、JSON.stringify()和eval()的作用详解
2016/04/03 Javascript
限时抢购-倒计时的完整实例(分享)
2017/09/17 Javascript
详解微信小程序支付流程与梳理
2019/07/16 Javascript
JavaScript鼠标悬停事件用法解析
2020/05/15 Javascript
JavaScript函数柯里化实现原理及过程
2020/12/02 Javascript
Python的Flask开发框架简单上手笔记
2015/11/16 Python
Python中import导入上一级目录模块及循环import问题的解决
2016/06/04 Python
Python+tkinter使用40行代码实现计算器功能
2018/01/30 Python
pycharm重置设置,恢复默认设置的方法
2018/10/22 Python
Python从函数参数类型引出元组实例分析
2019/05/28 Python
Python如何基于Tesseract实现识别文字功能
2020/06/05 Python
windows系统Tensorflow2.x简单安装记录(图文)
2021/01/18 Python
中国领先的汽车保养服务平台:途虎养车
2019/10/18 全球购物
主管会计岗位职责
2014/03/13 职场文书
儿童生日会策划方案
2014/05/15 职场文书
学校搬迁方案
2014/06/15 职场文书
2014年档案管理工作总结
2014/11/17 职场文书
2015年女职工工作总结
2015/05/15 职场文书
读书笔记格式
2015/07/02 职场文书
餐馆开业致辞
2015/08/01 职场文书
交通事故责任认定书
2015/08/06 职场文书
幼儿园语言教学反思
2016/02/23 职场文书
python基础详解之if循环语句
2021/04/24 Python