Python之读取配置文件

介绍

configparser模块主要用于读取配置文件,configparser模块支持读取.conf和.ini等类型的文件。
该模块的作用 就是使用模块中的RawConfigParser()、ConfigParser()、 SafeConfigParser()这三个方法(三者择其一),创建一个对象使用对象的方法对指定的配置文件做增删改查操作。

配置文件格式

[section] 
name=value
或者
name: value
"#" 和";" 表示注释

[DEFAULT] #设置默认的变量值,初始化
[My Section]
foodir: %(dir)s/whatever
dir=frob
long: this value continues
   in the next line

%(dir)s会被frob代替。默认值会以字典的形式传递给ConfigParser的构造器。section一般存放的哦内置目录下,如果切换到其他的目录需啊哟指定存放位置。

方法

下面这三种方式使用时,切记注意。在调用这三个函数时,切记这三个函数会将调用optionxform(),在传递键值对数据时,会将键名全部转化为小写
传递参数使用函数optionxform(),foo %(bar)s 和 foo %(BAR)s是相同的,optionxform()会将大写字母全部转换为小写。

RawConfigParser()

不支持可变参数,在section中不能存在%()s

ConfigParser.RawConfigParser([defaults[, dict_type[, allow_no_value]]]) 
    defaults : 如果指定默认值,则使用默认值的键值对
    dict_type:使用新的section的键值对
    allow_no_value :默认是False,如果是True,表示可以接收空值(None)
    return:对象

对象操作

对象的操作可以分为两大类,一种是对配置文件的操作,另一种是对读取后数据流的操作。

对配置文件的操作

读取配置文件
  • read(filenames):filesnames是一个列表,需要从文件加载初始值的应用程序应该在调用read()之前使用readfp()加载所需的文件或文件。
  • readfp(fp[, filename]):在fp中,从文件或文件类对象中读取和解析配置数据(只使用readline()方法)。如果文件名被省略,并且fp有一个name属性,它被用于文件名;默认值为< ? >。
写入配置文件
  • write(fileobject):将配置的表示写入指定的文件对象。这个表示可以由未来的read()调用解析。

对内存中数据流的操作

增加配置文件中的值
  • add_section(section):向实例添加一个section
删除配置文件中的值
  • remove_section(section):从配置中删除指定的section。如果这个部分确实存在,返回True;否则返回False。
  • remove_option(section, option):从指定的部分中删除指定的选项。如果该部分不存在,请提出NoSectionError。如果存在的选项被删除,返回True;否则返回False。
修改配置文件中的值
  • set(section, option, value):如果给定的部分存在,将给定的选项设置为指定的值
  • optionxform(option):也可以在一个实例上重新设置它,对于一个需要字符串参数的函数。例如,将其设置为str,将使选项名称区分大小写
查找配置文件中的值
  • defaults():返回包含实例范围默认值的字典。
  • sections():返回可用的section的列表;默认section不包括在列表中
  • options(section):返回指定section中可用的选项列表。
  • items(section):返回给定section中每个选项的(name,value)对的列表。
  • has_section(section):指示指定的section是否出现在配置中。默认的section未被确认
  • has_option(section, option):如果给定的section存在,并且包含给定的选项,则返回True;否则返回False
  • get(section, option):为指定的section获取一个选项值。
  • getint(section, option):它将指定section中的选项强制转换为整数
  • getfloat(section, option):它将指定section中的选项强制转换为浮点型
  • getboolean(section, option):强制转换为布尔型,”1”, “yes”, “true”, and “on”, 转换为True,”0”, “no”, “false”, and “off”, 转换为Falseo 其他返回ValueError.

ConfigParser()

在default中必须出现%()s

ConfigParser.ConfigParser([defaults[, dict_type[, allow_no_value]]]) 

对象操作

ConfigParser中包含RawConfigParser相同的方法,还有一部分增加的方法

  • get(section, option[, raw[, vars]]):为指定的section获取一个选项值。如果提供了vars,它必须是一个字典。该选项在vars(如果提供)、分段和默认值中查找,
  • items(section[, raw[, vars]]):返回给定section中每个选项的(名称、值)对的列表
  • add_set(section,option,value):对section中的option信息进行写入。本方法和set方法相同
    所有的“%”插值都在返回值中展开,除非原始的参数是真的。内插键的值与选项相同

SafeConfigParser()

更加智能化,在section中是否存在%()s会自动判断

ConfigParser.SafeConfigParser([defaults[, dict_type[, allow_no_value]]]) 

对象操作

set(section, option, value)
如果给定的部分存在,将给定的选项设置为指定的值;否则提高NoSectionError。值必须是字符串(str或unicode);如果没有,则会出现类型错误

异常

  • ConfigParser.Error:所有异常的基类
  • ConfigParser.NoSectionError:指定的section没有找到
  • ConfigParser.DuplicateSectionError:调用add_section() 时,section名称已经被使用
  • ConfigParser.NoOptionError:指定的参数没有找到
  • ConfigParser.InterpolationError:当执行字符串插值时出现问题时,出现异常的基类
  • ConfigParser.InterpolationDepthError:当字符串插值无法完成时,因为迭代次数超过了最大的范围,所以无法完成。InterpolationError的子类
  • InterpolationMissingOptionError:当引用的选项不存在时,会出现异常。InterpolationError的子类
  • ConfigParser.InterpolationSyntaxError:当产生替换的源文本不符合所需的语法时,就会出现异常。InterpolationError的子类。
  • ConfigParser.MissingSectionHeaderError:当试图解析一个没有分段标题的文件时,会出现异常。
  • ConfigParser.ParsingError:当试图解析文件时发生错误时,会出现异常
  • ConfigParser.MAX_INTERPOLATION_DEPTH:当raw参数为false时,get()的递归插值的最大深度。这只适用于ConfigParser类

实例

配置文件config.ini

[user]
user_name = Mr,X
password = 222

[connect]
ip = 127.0.0.1
port = 4723

初始化操作

import configparser
# 生成ConfigParser对象
config = configparser.ConfigParser()
# 读取配置文件
filename = 'config.ini'
config.read(filename, encoding='utf-8')

基本操作

获取节点sections

ConfigParser.sections(),以列表形式返回configparser对象的所有节点信息

# 获取所有节点
all_sections = config.sections()
print('sections: ', all_sections)   
# 结果sections:  ['user', 'connect']

获取指定节点的的所有配置信息

ConfigParser.items(section),以列表形式返回某个节点section对应的所有配置信息

# 获取指定节点的配置信息
items = config.items('user')
print(items)            
# 结果 [('user_name', "'Mr,X'"), ('password', "'222'")]

获取指定节点的options

ConfigParser.options(section),以列表形式返回某个节点section的所有key值

# 获取指定节点的options信息
options = config.options('user')
print(options)         
 # 结果 ['user_name', 'password']

获取指定节点下指定option的值

ConfigParser.get(section, option),返回结果是字符串类型
ConfigParser.getint(section, option),返回结果是int类型
ConfigParsergetboolean(section, option),返回结果是bool类型
ConfigParser.getfloat(section, option),返回结果是float类型

# 获取指定节点指定option的值
name = config.get('user', 'user_name')
print(name, type(name))            
# 结果 'Mr,X' <class 'str'>
port = config.getint('connect', 'port')
print(port, type(port))           
# 结果  4723 <class 'int'>

检查section或option是否存在

ConfigParser.has_section(section)
ConfigParser.has_option(section, option)
返回bool值,若存在返回True,不存在返回False

# 检查section是否存在
result = config.has_section('user')
print(result)   
# 结果 True
result = config.has_section('user1')
print(result)   
# 结果 False

# 检查option是否存在
result = config.has_option('user', 'user_name')
print(result)   # 结果 True
result = config.has_option('user', 'user_name1')
print(result)   # 结果 False
result = config.has_option('user1', 'user_name')
print(result)   # 结果 False

添加section

ConfigParser.add_section(section),如果section不存在,则添加节点section;若section已存在,再执行add操作会报错configparser.DuplicateSectionError: Section XX already exists

# 添加section
if not config.has_section('remark'):
    config.add_section('remark')
config.set('remark', 'info', 'ok')
config.write(open(filename, 'w'))
remark = config.items('remark')
print(remark)    
# 结果 [('info', 'ok')]

修改或添加指定节点下指定option的值

ConfigParser.set(section, option, value),若option存在,则会替换之前option的值为value;若option不存在,则会创建optiion并赋值为value

# 修改指定option的值
config.set('user', 'user_name', 'Mr L')
config.set('user', 'isRemember', 'True')
config.write(open(filename, 'w'))
# 重新查看修改后节点信息
items = config.items('user')
print(items)    
# 结果 [('user_name', 'Mr L'), ('password', '222'), ('isremember', 'True')]

删除section或option

ConfigParser.remove_section(section),若section存在,执行删除操作;若section不存在,则不会执行任何操作
ConfigParser.remove_option(section, option),若option存在,执行删除操作;若option不存在,则不会执行任何操作;若section不存在,则会报错configparser.NoSectionError: No section: XXX

# 删除section
config.remove_section('remark')         # section存在
config.remove_section('no_section')     # section不存在

# 删除option
config.remove_option('user', 'isremember')  # option存在
config.remove_option('user', 'no_option')   # option不存在
config.write(open(filename, 'w'))

all_sections = config.sections()
print(all_sections)     
# 结果 ['user', 'connect']
options = config.options('user')
print(options)      
# 结果 ['user_name', 'password']

写入内容

ConfigParser.write(open(filename, 'w')),对configparser对象执行的一些修改操作,必须重新写回到文件才可生效

config.write(open(filename, 'w'))