
python读取ini配置的类封装
读取所有section的名称列表 阅读指定section的项目数据 将指定section转换为字典格式 获取所有section的所有项目数据 添加新的section 添加新key-value项 调试配置文件操作模式
发布日期:2021-05-10 04:40:01
浏览次数:20
分类:精选文章
本文共 2563 字,大约阅读时间需要 8 分钟。
类文字优化
import configparserimport osclass IniCfg(object): 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 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() def readOneSection(self, section): try: item = self.conf.items(section) except Exception: print(">> 无此section,请核对{%s}" % section) return None return item 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 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 def removeItem(self, section, key): if not self.checkSection(section): return self.conf.remove_option(section, key) def removeSection(self, section): if not self.checkSection(section): return self.conf.remove_section(section) def addSection(self, section): self.conf.add_section(section) def addItem(self, section, key, value): if not self.checkSection(section): return self.conf.set(section, key, value) def actionOperate(self, mode): if mode == 'r+': self.conf.write(open(self.cfgpath, "r+", encoding="utf-8")) elif mode == 'w': self.conf.write(open(self.cfgpath, "w")) elif mode == 'a': self.conf.write(open(self.cfgpath, "a"))
测试ini
在ini文件【config.ini】中,测试以下配置:```ini[chaoji]chaoji_username = 123chaoji_password = 456[my]soft_id = 789sleeptime = asdcnt_count = zxc
测试内容包括:
通过以上操作,可以实现对ini文件的完整管理,包括读写操作和数据处理功能。测试结果表明,类功能完善,活跃性较高,适合多种配置场景需求。
发表评论
最新留言
网站不错 人气很旺了 加油
[***.192.178.218]2025年05月07日 02时32分12秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Python字符串操作之字符串分割与组合
2019-03-17
MATLAB截断数组
2019-03-17
tf.parse_single_example()
2019-03-17
tensorflow为什么要用placeholder()
2019-03-17
latex表示极限
2019-03-17
tf.tuple
2019-03-17
在VSCode上配置编写LaTex文档的环境
2019-03-17
C++实现二叉树的最近公共祖先
2019-03-17
CentOS7安装mysql5.6
2019-03-17
从git上导入项目到idea,出现某些依赖找不到了
2019-03-17
SpringCloud--09服务链路追踪Sleuth
2019-03-17
windows下通过cmd杀死进程的方法
2019-03-17