Python read ini configuration class encapsulation code instance


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


# coding:utf-8
import configparser
import os

class IniCfg():
  def __init__(self):
    self.conf = configparser.ConfigParser()
    self.cfgpath = ''

  def checkSection(self, 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, encoding="utf-8")
    return self.conf.sections()

  #Read a section. The object in the list is Yuanzu
  def readOneSection(self, section):
      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()
    return res_1

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

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

  #Add a section
  def addSection(self, section):

  #Add key and value to the section
  def addItem(self, section, key, value):
    if not self.checkSection(section):
    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)
content = inicfg.readOneSection('chaoji')
dic = inicfg.prettySecToDic('chaoji')
dic = inicfg.prettySecsToDic()

content = inicfg.readOneSection('chaoji')

Test ini

chaoji_username = 123
chaoji_password = 456
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.

Recommended Today

Common auxiliary classes

CountDownLatch Subtraction counter import java.util.concurrent.CountDownLatch; //Counter public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { //The total number is 6. It can be used when the task must be performed CountDownLatch countDownLatch = new CountDownLatch(6); for (int i = 0; i < 6; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName()+” Go out”); countDownLatch.countDown(); },String.valueOf(i)).start(); […]