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的Tornado框架中的协程异步实现原理
Apr 23 Python
python安装与使用redis的方法
Apr 19 Python
Python 3.x 连接数据库示例(pymysql 方式)
Jan 19 Python
简单谈谈Python中的几种常见的数据类型
Feb 10 Python
Python读取word文本操作详解
Jan 22 Python
Python iter()函数用法实例分析
Mar 17 Python
python将处理好的图像保存到指定目录下的方法
Jan 10 Python
python使用Pandas库提升项目的运行速度过程详解
Jul 12 Python
Apache部署Django项目图文详解
Jul 30 Python
pytorch 固定部分参数训练的方法
Aug 17 Python
python实现udp传输图片功能
Mar 20 Python
最新pycharm安装教程
Nov 18 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
单位速度在实战中的运用
2020/03/04 星际争霸
PHP 多进程 解决难题
2009/06/22 PHP
程序员编程十条戒律
2009/07/09 PHP
php is_file()和is_dir()用于遍历目录时用法注意事项
2010/03/02 PHP
php数据库操作model类(使用__call方法)
2016/11/16 PHP
php实现异步将远程链接上内容(图片或内容)写到本地的方法
2016/11/30 PHP
Yii框架参数化查询中IN查询只能查询一个的解决方法
2017/05/20 PHP
php微信开发之关注事件
2018/06/14 PHP
PHP实现统计代码行数小工具
2019/09/19 PHP
jQuery不使用插件及swf实现无刷新文件上传
2014/12/08 Javascript
JQuery删除DOM节点的方法
2015/06/11 Javascript
Vue2.0用户权限控制解决方案
2017/11/29 Javascript
Vue实现表格批量审核功能实例代码
2019/05/28 Javascript
vue 解决form表单提交但不跳转页面的问题
2019/10/30 Javascript
javascript History对象原理解析
2020/02/17 Javascript
[55:47]DOTA2上海特级锦标赛C组小组赛#2 LGD VS Newbee第三局
2016/02/27 DOTA
python reduce 函数使用详解
2017/12/05 Python
Python基于回溯法解决01背包问题实例
2017/12/06 Python
Python加载带有注释的Json文件实例
2018/05/23 Python
详解pandas如何去掉、过滤数据集中的某些值或者某些行?
2019/05/15 Python
pyhton中__pycache__文件夹的产生与作用详解
2019/11/24 Python
Python 实现网课实时监控自动签到、打卡功能
2020/03/12 Python
如何基于线程池提升request模块效率
2020/04/18 Python
keras 自定义loss层+接受输入实例
2020/06/28 Python
一些常用的HTML5模式(pattern) 总结
2015/07/14 HTML / CSS
个人求职简历的自我评价范文
2013/10/09 职场文书
商场消防管理制度
2014/01/12 职场文书
青年文明号事迹材料
2014/01/18 职场文书
产品质量保证书范本
2015/02/27 职场文书
家装业务员岗位职责
2015/04/03 职场文书
机关单位保密工作责任书
2015/05/11 职场文书
毕业生政审意见范文
2015/06/04 职场文书
投诉书格式范本
2015/07/02 职场文书
2019年家电促销广告语集锦
2019/10/21 职场文书
HTML中table表格拆分合并(colspan、rowspan)
2021/04/07 HTML / CSS
Python使用pyecharts控件绘制图表
2022/06/05 Python