一、简介
概要:配置文件解析器
二、使用
import configParser
config=configParser.configParser()
三、方法
- config.read(filename, encoding='utf-8') 读取配置文件
- config.sections() 获取配置文件下的所有配置
- config.items(section) 获取指定配置信息
- config.options(section) 获取指定配置所有的key
- config.get(section, option) 获取指定配置指定option的值,字符串类型
- config.getint('connect', 'port')获取指定配置指定option的值,整数
- config.getboolean(section, option) 获取指定配置指定option的值,布尔
- config.getfloat(section, option) 获取指定配置指定option的值,浮点数
- config.has_option(section, option) 检查section或option是否存在
- config.add_section(section)添加配置
- config.set(section, option, value)改或添加指定配置下指定option的值
- config.remove_option(section, option)删除配置
- config.remove_option(section, option) 删除指定配置的option,如果配置不存在会报错
- config.write(open(filename, 'w')) 执行的一些修改操作,必须重新写回到文件才可生效
- config.read_dict({'option1':{},'option2':{}}) 一次生成多个配置
- config.defaults()返回默认部分的字典
- config.readfp(fp[, filename])读取并解析 fp,fp 可以是文件也可以是文件对象
- config.optionxform = str 保留键值大小写
四、属性
- configParser.Error:异常基类
- configParser.NoSectionError:没有指定 section 时抛出
- configParser.DuplicateSectionError:调用 add_section() 时,指定 section 已经存在
- configParser.NoOptionError:指定 section 中没有 option
- configParser.InterpolationError:格式化字符串失败时的基类
- configParser.InterpolationDepthError:格式化字符串时超过最大迭代深度
- configParser.InterpolationMissingOptionError:格式化字符串的其中一个及以上属性缺失
- configParser.InterpolationSyntaxError:格式化字符串时语法错误
- configParser.MissingSectionHeaderError:解析没有 section 标题名的文件时抛出
- configParser.ParsingError:解析文件错误
该文章介绍了Python中的configParser模块,用于解析和操作配置文件。主要方法包括读取配置文件、获取配置项、设置和修改选项值、删除选项以及处理配置文件的异常情况。此外,还涉及了如何处理配置文件的大小写敏感性。
161

被折叠的 条评论
为什么被折叠?



