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

 更新时间:2020年01月08日 09:57:59   作者:小锋学长  
这篇文章主要介绍了python读取ini配置的类封装代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

这篇文章主要介绍了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实现嵌套列表及字典并按某一元素去重复功能示例

    这篇文章主要介绍了Python实现嵌套列表及字典并按某一元素去重复功能,涉及Python列表嵌套列表、列表嵌套字典,及按照某一元素去重复的相关操作方法,需要的朋友可以参考下
    2017-11-11
  • Pytorch中的variable, tensor与numpy相互转化的方法

    Pytorch中的variable, tensor与numpy相互转化的方法

    这篇文章主要介绍了Pytorch中的variable, tensor与numpy相互转化的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • python中关于eval函数的使用及说明

    python中关于eval函数的使用及说明

    这篇文章主要介绍了python中关于eval函数的使用及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-05-05
  • 如何让Python在HTML中运行

    如何让Python在HTML中运行

    这个名为PyScript的框架,其核心目标是为开发者提供在标准HTML中嵌入Python代码的能力,使用 Python调用JavaScript函数库,并以此实现利用Python创建Web应用的功能,本文给大家介绍Python HTML运行的案例解析,感兴趣的朋友一起看看吧
    2022-05-05
  • yolov5返回坐标的方法实例

    yolov5返回坐标的方法实例

    这篇文章主要给大家介绍了关于yolov5返回坐标的相关资料,文中通过实例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2022-03-03
  • 关于python常见异常以及处理方法

    关于python常见异常以及处理方法

    这篇文章主要介绍了关于python常见异常以及处理方法,python用异常对象(exception object)来表示异常情况。遇到错误后,会引发异常,需要的朋友可以参考下
    2023-04-04
  • Python中模拟enum枚举类型的5种方法分享

    Python中模拟enum枚举类型的5种方法分享

    这篇文章主要介绍了Python中模拟enum枚举类型的5种方法分享,本文直接给出实现代码,需要的朋友可以参考下
    2014-11-11
  • python3 实现口罩抽签的功能

    python3 实现口罩抽签的功能

    这篇文章主要介绍了python3 实现 口罩抽签的功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-03-03
  • 神经网络算法RNN实现时间序列预测

    神经网络算法RNN实现时间序列预测

    这篇文章主要为大家介绍了神经网络算法RNN实现时间序列预测示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-04-04
  • python属于解释语言吗

    python属于解释语言吗

    在本篇文章里小编给大家分享了关于python关于是否为解释语言的知识点,有兴趣的朋友们可以学习下。
    2020-06-06

最新评论