python读取ini配置的类封装
发布日期:2021-05-10 04:40:01 浏览次数:20 分类:精选文章

本文共 2563 字,大约阅读时间需要 8 分钟。

类文字优化

import configparser
import os
class 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 = 123
chaoji_password = 456
[my]
soft_id = 789
sleeptime = asd
cnt_count = zxc

测试内容包括:

  • 读取所有section的名称列表
  • 阅读指定section的项目数据
  • 将指定section转换为字典格式
  • 获取所有section的所有项目数据
  • 添加新的section
  • 添加新key-value项
  • 调试配置文件操作模式
  • 通过以上操作,可以实现对ini文件的完整管理,包括读写操作和数据处理功能。测试结果表明,类功能完善,活跃性较高,适合多种配置场景需求。
    上一篇:ESP32蓝牙的Gatt Client的例子演练
    下一篇:[开源]蚂蚁森林自动收能量,自动解锁和自动触发

    发表评论

    最新留言

    网站不错 人气很旺了 加油
    [***.192.178.218]2025年05月07日 02时32分12秒