ini配置文件与ConfigParser对象

以你之姓@ 2022-02-05 12:04 360阅读 0赞

ini配置文件与ConfigParser对象

目录结构

  • ini配置文件与ConfigParser对象
  • ini配置文件简介
  • configparser模块中的ConfigParser类
    • 常用方法
      • 读取和写入
      • 获取值
      • 添加,修改,移除
      • 判断

ini配置文件简介

  1. [DEFAULT]
  2. a = test
  3. [mysql]
  4. default-character-set = utf8
  5. [mysqld]
  6. datadir = /dbserver/data
  7. port = 33060
  8. character-set-server=utf8
  1. 中括号[]里面的内容称为section,翻译为:节,区,段。
  2. 每一个section内,都是key=value形成的键值对,key称为option选项
    注意:DEFAULT是缺省的section的名字,必须大写。当section中没有找到对应的键值对时,默认会从DEFAULT中寻找,如果都没有就找不到。

configparser模块中的ConfigParser类

  1. ConfigParser类帮助处理ini配置文件。可以将section当做key,section存储着键值对组成的字典。默认使用有序字典存储。

    • 使用简单示例

    from configparser import ConfigParser
    cfg = ConfigParser()
    cfg.read(“mysql.ini”)
    for i in cfg:

    1. print(i)
    2. for k,v in cfg.items(i):
    3. print(k,":",v)
    4. print()
    • 输出结果为:
      ini001

常用方法

读取和写入

  • read(filenames,encoding=None) #读取ini文件,可以是单个文件,也可以是文件列表。可以指定文件编码

    • filenames :单个文件,或者是多个文件组成的文件列表
    • encoding:文件编码,读取文件时的文件编码,默认为None。
    • 原码如下

      def read(self, filenames, encoding=None):

      1. #如果传入的值时str,或者bytes,直接将filenames 变成列表
      2. if isinstance(filenames, (str, bytes, os.PathLike)):
      3. filenames = [filenames]
      4. read_ok = []
      5. for filename in filenames:
      6. try:
      7. with open(filename, encoding=encoding) as fp:
      8. self._read(fp, filename)
      9. except OSError:
      10. continue
      11. if isinstance(filename, os.PathLike):
      12. filename = os.fspath(filename)
      13. read_ok.append(filename)
      14. return read_ok
  • read_file(f,soure=None) #从f文件流中读取内容。

    • f:文件流,要读取的文件的文件流对象
    • soure: 读取的文件名,默认为None,会从文件对象中f.name获取。
    • 简单示例:

      with open(“mysql.ini”) as f:

      1. cfg.read_file(f,source="gdy.ini")

      for i in cfg:

      1. print(i)
      2. for k,v in cfg.items(i):
      3. print(k,":",v)
      4. print()
  • read_string(string,source=””) #从string字符串中读取ini配置信息

    • string #要读取的string类型的字符串
    • source #
    • 简单示例:

      from configparser import ConfigParser
      string = “”” [DEFAULT] like=”吃北京烤鸭” ect=”喝青岛啤酒” [two] name=”张三” age=”15” like=”吃烤鸭” “””
      cfg = ConfigParser()
      cfg.read_string(string)

      遍历

      for i in cfg:

      1. print(i)
      2. for k,v in cfg.items(i):
      3. print(k,":",v)
      4. print()

      写入配置文件

      with open(“gdy.ini”,”w”,encoding=”utf-8”) as f:

      1. cfg.write(f)
    • 输出结果为:
      ini003

  • read_dict(dictionary,source=””) #从字典中读取ini配置信息

    • dictionary:字典类型的ini配置信息
    • source:
    • 简单示例:

      from configparser import ConfigParser
      dt = { “DEFAULT”:{ “like”:”打篮球”,”ect”:”吃北京烤鸭”},”mysql”:{ “name”:”张三”,”age”:16}}
      cfg = ConfigParser()

      从字典种读取ini配置信息

      cfg.read_dict(dt)

      遍历

      for i in cfg:

      1. print(i)
      2. for k,v in cfg.items(i):
      3. print(k,":",v)
      4. print()

      写入配置文件

      with open(“gdy.ini”,”w”,encoding=”utf-8”) as f:

      1. cfg.write(f)
    • 输出结果为:
      ini002

  • write(fileobject,space_around_delimiters=True) #将当前config的所有内容写入fileobject中,一般open函数使用w模式。

    • fileobject:要写入文件的文件描述符对象。只能以文本模式t打开
    • space_around_delimiters: 默认值True。是否在key,=,value之间使用空格隔开。True表示添加空格

      • True。添加空格分离key,=,value即:key = value
      • False。不添加空格即:key=value
    • 上面读取中已经包含了写入例子,这里不再演示。

获取值

  • sections()->list #返回section列表,缺省section不包括在内

    • list :列表,由section名称组成。但不包含DEFAULT名称
  • options(section)->list #返回section的所有option,会追加缺省section的option

    • section :str类型的section名称
    • list:返回自定section的key名称,会包含DEFAULT中设置的默认key名称
  • get(section,option,*,raw=False,vars=None[,fallabck]) #从指定的字段选项上取值,如果找到返回,如果没有就找到,就去DEFAULT段去找。

    • section: str类型,需要寻找值所属section
    • option:str类型,需要寻找值所属的option
  • getint(section,option,*,raw=False,vars=None[,fallback])->int #获取值返回int类型
  • getfloat(section,option,*,raw=False,vars=None[,fallback])->float #获取值返回float类型
  • getboolean(section,option,*,raw=False,vars=None[,fallback])->bool #获取值返回bool类型
  • items(raw=False,vars=None) #返回section的名称及名称对应的section对象
  • items(section,raw=False,vars=None) #返回指定section的键值对组成的二元组

    • items()与items(section)是一个方法,只是用代码实现了section的默认值返回规则。原码如下:

      def items(self, section=_UNSET, raw=False, vars=None):

      1. """Return a list of (name, value) tuples for each option in a section. All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument `raw' is true. Additional substitutions may be provided using the `vars' argument, which must be a dictionary whose contents overrides any pre-existing defaults. The section DEFAULT is special. """
      2. if section is _UNSET:
      3. return super().items()
      4. d = self._defaults.copy()
      5. try:
      6. d.update(self._sections[section])
      7. except KeyError:
      8. if section != self.default_section:
      9. raise NoSectionError(section)
      10. # Update with the entry specific variables
      11. if vars:
      12. for key, value in vars.items():
      13. d[self.optionxform(key)] = value
      14. value_getter = lambda option: self._interpolation.before_get(self,
      15. section, option, d[option], d)
      16. if raw:
      17. value_getter = lambda option: d[option]
      18. return [(option, value_getter(option)) for option in d.keys()]
  • 简单综合示例:

    from configparser import ConfigParser
    string = “”” [DEFAULT] like=”吃北京烤鸭” ect=”喝青岛啤酒” [two] name=”张三” age=”15” like=”吃烤鸭” [one] name = “李四” age = “18” show = “跳舞” “””
    cfg = ConfigParser()
    cfg.read_string(string)
    sct = cfg.sections()
    print(“执行方法sections(),返回值类型”,type(sct),”返回值:”,sct)

    print(“————————“)
    print(“开始测试options()”)
    for i in sct:

    1. op = cfg.options(i)
    2. #注意options返回key中会包含默认的key
    3. print(type(op),op)

    print(“———————————-“)
    print(“开始测试get”)
    print(cfg.get(“one”,”name”),cfg.get(“one”,”ect”))

    print(“—————————“)
    print(“开始测试items()”)
    itm = cfg.items()
    print(type(itm),itm)
    for i in itm:

    1. print(i)
    2. for k in i[1]:
    3. print("\t",k)

    print(“———————————“)
    print(“开始测试items(section)”)
    secitm = cfg.items(“one”)
    print(type(secitm),secitm)
    for i in secitm:

    1. print(i)
  • 输出结果为:
    ini004

添加,修改,移除

  • add_section(section_name) #增加一个section
  • set(section,option,value) #section存在的情况下,写入option=vallue,要求option、value必须是字符串
  • remove_section(section) #移除section及其所有的option

判断

  • has_section(section_name) #判断section是否存在
  • has_option(section,option) #判断section是否存在这个option

发表评论

表情:
评论列表 (有 0 条评论,360人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Python--ini配置文件

    你知道配置文件的好处吗? 在这里简单的说一下: 你是否还在将值写死,无法做到灵活变动。 你是否还在将一个个配置参数写成固定值,而后需要变动的时候疯狂的找py文件然后CV。