三种类介绍

RawCnfigParser 是最基础的INI文件读取类

ConfigParser类扩展了RawConfigParser的一些接口方法,添加了一些可选参数。

    get(section, option [, raw[, vars]])
    获取给定section下的option的值,所以“%”占位符在返回值中被填补,基于构造时传递的默认值,就像option,vars也被提供,除非raw参数为true。

    items(section, [, raw[, vars]])
    返回给定section下的所以option的(name, value)对列表。可选参数同get方法,2.3版本新增。

SafeConfigParser对象中的方法 

    SafeConfigParser类实现了ConfigParser相同的接口,新增如下方法:

    set(section, option, value)
    如果给定的section存在,给option赋值;否则抛出NoSectionError异常。Value值必须是字符串(str或unicode);如果不是,抛出TypeError异常,2.4版本新增

  

常用方法

config.read(filename,encoding) 直接读取ini文件内容,finlename 文件地址,encoding 文件编码格式
config.sections() 得到所有的section,并以列表的形式返回
config.options(section) 得到该section的所有option
config.items(section) 得到该section的所有键值对
config[section][option] 读取section中的option的值
config.get(section,option) 得到section中option的值,返回为string类型
config.getint(section,option) 得到section中option的值,返回为int类型
config.getboolean(section,option) 得到section中option的值,返回为bool类型
config.getfloat(section,option) 得到section中option的值,返回为float类型

  

样例

import configparser
config=configparser.RawConfigParser()
config.read(conf_file,encoding="utf-8")
for section in config.sections():
    for k,v in config.items(section):
        print(k,v)

  

 

 posted on 2024-04-24 09:57  boye169  阅读(78)  评论(0编辑  收藏  举报