Python read ini configuration class encapsulation code instance

Time:2021-6-8

This article mainly introduces the python read ini configuration class encapsulation code example, the article through the example code is very detailed, for everyone’s study or work has a certain reference learning value, need friends can refer to

This is the basic encapsulation, without considering too much exception handling

class

# 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 ("> > there is no such section, please check the section of [% s]%)
      return None
    return True

  #Read ini and get all section names
  def readSectionItems(self, cfgpath):
    if not os.path.isfile(cfgpath):
      Print ("> > there is no such file, please check the path: [% s]% cfgpath)
      return None
    self.cfgpath = cfgpath
    self.conf.read(cfgpath, encoding="utf-8")
    return self.conf.sections()

  #Read a section. The object in the list is Yuanzu
  def readOneSection(self, section):
    try:
      item = self.conf.items(section)
    except Exception:
      Print ("> > there is no such section, please check the section of [% s]%)
      return None
    return item

  #Read a section into the dictionary
  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

  #Read all sections into the dictionary
  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

  #Delete an item in a section (marked by key value)
  def removeItem(self, section, key):
    if not self.checkSection(section):
      return
    self.conf.remove_option(section, key)

  #Delete the entire section
  def removeSection(self, section):
    if not self.checkSection(section):
      return
    self.conf.remove_section(section)

  #Add a section
  def addSection(self, section):
    self.conf.add_section(section)

  #Add key and value to the section
  def addItem(self, section, key, value):
    if not self.checkSection(section):
      return
    self.conf.set(section, key, value)

  #Write write, remove and set methods do not really modify the INI file content. Only when the conf.write() method is executed, the INI file content will be modified
  def actionOperate(self, mode):
    if mode == 'r+':
      Conf.write (open (self. Cfgpath, "R +", encoding = "UTF-8"))? Modify mode
    elif mode == 'w':
      Conf.write (open (self. Cfgpath, "W")) # delete the original file and write it again
    elif mode == 'a':
      Conf.write (open (self. Cfgpath, "a"))? Append mode write

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)

Test ini


[chaoji]
chaoji_username = 123
chaoji_password = 456
[my]
soft_id     = 789
sleeptime     = asd
cnt_count     = zxc

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.