ini配置文件与ConfigParser对象
ini配置文件与ConfigParser对象
目录结构
- ini配置文件与ConfigParser对象
- ini配置文件简介
- configparser模块中的ConfigParser类
- 常用方法
- 读取和写入
- 获取值
- 添加,修改,移除
- 判断
ini配置文件简介
[DEFAULT]
a = test
[mysql]
default-character-set = utf8
[mysqld]
datadir = /dbserver/data
port = 33060
character-set-server=utf8
- 中括号[]里面的内容称为section,翻译为:节,区,段。
- 每一个section内,都是key=value形成的键值对,key称为option选项
注意:DEFAULT是缺省的section的名字,必须大写。当section中没有找到对应的键值对时,默认会从DEFAULT中寻找,如果都没有就找不到。
configparser模块中的ConfigParser类
ConfigParser类帮助处理ini配置文件。可以将section当做key,section存储着键值对组成的字典。默认使用有序字典存储。
- 使用简单示例
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read(“mysql.ini”)
for i in cfg:print(i)
for k,v in cfg.items(i):
print(k,":",v)
print()
- 输出结果为:
常用方法
读取和写入
read(filenames,encoding=None) #读取ini文件,可以是单个文件,也可以是文件列表。可以指定文件编码
- filenames :单个文件,或者是多个文件组成的文件列表
- encoding:文件编码,读取文件时的文件编码,默认为None。
原码如下
def read(self, filenames, encoding=None):
#如果传入的值时str,或者bytes,直接将filenames 变成列表
if isinstance(filenames, (str, bytes, os.PathLike)):
filenames = [filenames]
read_ok = []
for filename in filenames:
try:
with open(filename, encoding=encoding) as fp:
self._read(fp, filename)
except OSError:
continue
if isinstance(filename, os.PathLike):
filename = os.fspath(filename)
read_ok.append(filename)
return read_ok
read_file(f,soure=None) #从f文件流中读取内容。
- f:文件流,要读取的文件的文件流对象
- soure: 读取的文件名,默认为None,会从文件对象中f.name获取。
简单示例:
with open(“mysql.ini”) as f:
cfg.read_file(f,source="gdy.ini")
for i in cfg:
print(i)
for k,v in cfg.items(i):
print(k,":",v)
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:
print(i)
for k,v in cfg.items(i):
print(k,":",v)
print()
写入配置文件
with open(“gdy.ini”,”w”,encoding=”utf-8”) as f:
cfg.write(f)
输出结果为:
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:
print(i)
for k,v in cfg.items(i):
print(k,":",v)
print()
写入配置文件
with open(“gdy.ini”,”w”,encoding=”utf-8”) as f:
cfg.write(f)
输出结果为:
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):
"""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. """
if section is _UNSET:
return super().items()
d = self._defaults.copy()
try:
d.update(self._sections[section])
except KeyError:
if section != self.default_section:
raise NoSectionError(section)
# Update with the entry specific variables
if vars:
for key, value in vars.items():
d[self.optionxform(key)] = value
value_getter = lambda option: self._interpolation.before_get(self,
section, option, d[option], d)
if raw:
value_getter = lambda option: d[option]
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:op = cfg.options(i)
#注意options返回key中会包含默认的key
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:print(i)
for k in i[1]:
print("\t",k)
print(“———————————“)
print(“开始测试items(section)”)
secitm = cfg.items(“one”)
print(type(secitm),secitm)
for i in secitm:print(i)
输出结果为:
添加,修改,移除
- 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
还没有评论,来说两句吧...