Python 之configparser读取配置操作类

  一、为什么要封装

  我们为什么要封装,我相信你们在项目开发过程中深有体会,那么这个读取配置工具类,又是为了什么?

  为了项目参数配置的灵活性,不要改动到源码

  为了信息的安全(一定层面的),体现代码重用性

  二、封装读取配置文件的操作类

  from configparser import ConfigParser

  # 2.配置文件由哪几部分构成?

  # a、sectionso区域

  # b、option选择项:value值

  class conf_read(object):

  '''封装读取confi/ini等配置文件的操作类'''

  def __init__(self,conf_name,encoding="utf-8):

  # 创建ConfigParser解析对象

  self.conf=ConfigParser()

  self.conf_name=conf_name

  self.encoding=encoding

  # 读取指定配置文件

  self.conf.read(self.conf_name,encoding=self.encoding)

  # 读取数据:查看区域

  self.sections=self.conf.sections()

  self.options=[]

  def get(self,section,option):

  return self.conf.get(section,option)

  def get_int(self,section,option):

  return self.conf.getint(section,option)

  def get_float(self,section,option):

  return self.conf.getfloat(section,option)

  def get_bool(self,section,option):

  return self.conf.getboolean(section,option)

  优化上面封装的读取配置操作类郑州妇科医院哪家好 http://mobile.chfk120.com/

  看上面封装的读取配置操作类,每个方法都只是return简单的一句话源码,其实都只是继承配置类中最原始的方法,所以不用再重复造轮子

  from configparser import ConfigParser

  class conf_read(ConfigParser):

  def __init__(self,conf_name,encoding="utf-8"):

  # 创建ConfigParser解析对象

  super().__init__()

  self.conf_name=conf_name

  self.encoding=encoding

  # 读取指定配置文件

  self.read(self.conf_name,encoding=self.encoding)

  def write_data(self.conf_name)

  '''往配置文件中写入数据'''

  self.set(section, option, value)

  self.write(open(self.file_name,"w",encoding=self.encoding))

  这样看代码,是不是比上一个版本简洁多了,至于读取配置文件的方法,使用继承ConfigParser类的原始方法就好了:

  conf=conf_read("common.conf",encoding="utf-8")

  conf.get("section","option")

原文地址:https://www.cnblogs.com/djw12333/p/11988123.html