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中的字符串知识点
Apr 14 Python
python将字符串转换成数组的方法
Apr 29 Python
python:socket传输大文件示例
Jan 18 Python
python利用不到一百行代码实现一个小siri
Mar 02 Python
Django之无名分组和有名分组的实现
Apr 16 Python
Python3.5内置模块之random模块用法实例分析
Apr 26 Python
Python使用gluon/mxnet模块实现的mnist手写数字识别功能完整示例
Dec 18 Python
django迁移文件migrations的实现
Mar 31 Python
如何配置关联Python 解释器 Anaconda的教程(图解)
Apr 30 Python
Python hashlib模块的使用示例
Oct 09 Python
Python经典五人分鱼实例讲解
Jan 04 Python
Python实现查询剪贴板自动匹配信息的思路详解
Jul 09 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
实现了一个PHP5的getter/setter基类的代码
2007/02/25 PHP
CI框架中集成CKEditor编辑器的教程
2014/06/09 PHP
PHP安全的URL字符串base64编码和解码
2014/06/19 PHP
PHP中file_get_contents高?用法实例
2014/09/24 PHP
php自动提交表单的方法(基于fsockopen与curl)
2016/05/09 PHP
PHP xpath提取网页数据内容代码解析
2020/07/16 PHP
PJBlog插件 防刷新的在线播放器
2006/10/25 Javascript
js 浮动层菜单收藏
2009/01/16 Javascript
IE浏览器打印的页眉页脚设置解决方法
2009/12/08 Javascript
用js来刷新当前页面保留参数的具体实现
2013/12/23 Javascript
Bootstrap 3的box-sizing样式导致UEditor控件的图片无法正常缩放的解决方案
2016/09/15 Javascript
微信小程序开发之入门实例教程篇
2017/03/07 Javascript
node puppeteer(headless chrome)实现网站登录
2018/05/09 Javascript
你可能不知道的CORS跨域资源共享
2019/03/13 Javascript
php结合js实现多条件组合查询
2019/05/28 Javascript
微信小程序tabBar 返回tabBar不刷新页面
2019/07/25 Javascript
Vue监听滚动实现锚点定位(双向)示例
2019/11/13 Javascript
JavaScript实现Tab标签页切换的最简便方式(4种)
2020/06/28 Javascript
js属性对象的hasOwnProperty方法的使用
2021/02/05 Javascript
Python 学习笔记
2008/12/27 Python
python如何读写json数据
2018/03/21 Python
浅析Python四种数据类型
2018/09/26 Python
python 实现交换两个列表元素的位置示例
2019/06/26 Python
构建高效的python requests长连接池详解
2020/05/02 Python
浅谈python 类方法/静态方法
2020/09/18 Python
python 调整图片亮度的示例
2020/12/03 Python
唤醒头发毛囊的秘密武器:Grow Gorgeous
2016/08/28 全球购物
DKNY品牌官网:纽约大都会时尚风格
2016/10/20 全球购物
CHRONEXT英国:您的首选奢华腕表目的地
2020/03/30 全球购物
高中军训感言1000字
2014/03/01 职场文书
信用社竞聘演讲稿
2014/05/16 职场文书
员工自我评价范文
2015/03/11 职场文书
庆祝教师节新闻稿
2015/07/17 职场文书
2016年小学生教师节广播稿
2015/12/18 职场文书
高性能跳频抗干扰宽带自组网电台
2022/02/18 无线电
MySQL 数据库范式化设计理论
2022/04/22 MySQL