ConfigParser Objects:
class configparser.ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})
该模块支持读取类似如上格式的配置文件,如 windows 下的 .conf 及 .ini 文件等
- defaults():返回一个包含实例范围默认值的词典
- sections(): 得到所有的section,并以列表的形式返回
- add_section(section):添加一个新的section
- has_section(section):判断是否有section
- options(section) 得到该section的所有option
- has_option(section, option):判断如果section和option都存在则返回True否则False
- read(filenames, encoding=None):直接读取配置文件内容
- read_file(f, source=None):读取配置文件内容,f必须是unicode
- read_string(string, source=’’):从字符串解析配置数据
- read_dict(dictionary, source=’’)从词典解析配置数据
- get(section, option, *, raw=False, vars=None[, fallback]):得到section中option的值,返回为string类型
- getint(section,option) 得到section中option的值,返回为int类型
- getfloat(section,option)得到section中option的值,返回为float类型
- getboolean(section, option)得到section中option的值,返回为boolean类型
- items(raw=False, vars=None)和items(section, raw=False, vars=None):列出选项的名称和值
- set(section, option, value):对section中的option进行设置
- write(fileobject, space_around_delimiters=True):将内容写入配置文件。
- remove_option(section, option):从指定section移除option
- remove_section(section):移除section
- optionxform(option):将输入文件中,或客户端代码传递的option名转化成内部结构使用的形式。默认实现返回option的小写形式;
- readfp(fp, filename=None)从文件fp中解析数据
基础读取配置文件
- -read(filename) 直接读取文件内容
- -sections() 得到所有的section,并以列表的形式返回
- -options(section) 得到该section的所有option
- -items(section) 得到该section的所有键值对
- -get(section,option) 得到section中option的值,返回为string类型
- -getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。
基础写入配置文件
- -write(fp) 将config对象写入至某个 .init 格式的文件
- -add_section(section) 添加一个新的section
- -set( section, option, value 对section中的option进行设置,需要调用write将内容写入配置文件
- -remove_section(section) 删除某个 section
- -remove_option(section, option) 删除某个 section 下的 option
- 实例一:
import configparser # 1.创建cofigparser实例 config=configparser.ConfigParser() #config={},整体相当于一个空字典 config['DEFAULT']={'ServerAliveInterval' : 45, 'Compression':'yes', 'CompressionLevel' :9, 'ForwardX11' : 'yes'} with open('sample.ini','w+') as f: config.write(f) # 将对象写入配置文件 congfig.write(fp)