python中configpraser模块

configparser   模块

解析配置文件模块

什么是配置文件?

用于编写程序的配置信息的文件

什么是配置信息?

为了提高程序的扩展性

#configparser模块的使用
#首先我们需要知道配置文件怎么写,配置文件的组成
[section1]   #分区1
k1 = v1      #分区1内的选项
k2:v2
user=ming
age=25
is_admin=true
salary=31
​
[section2]   #分区2
k1 = v1      #分区2的选项
#分区不能重名,同一分区内的选项不能一样
#使用
#1.首先创建一个配置文件解析器
cfg = configparser.ConfigParser()  #创建配置文件解析器
cfg.read('test.cfg', encoding='utf-8')  #读取名为test的配置文件,编码格式为utf-8
​
​
#1.读取文件
#获取分区
res = cfg.sections()     #查看所有分区
print(res)               #[section1 , stection2]
#获取分区下的某一选项
res = cfg.get('section1', 'user')  #查看分区section1下的user对应的值 
print(res)               #ming   type为字符串类型
#获取分区下所有的选项
res = cfg.options('section1')  #查看section1下的所有选项
print(res)     #['k1', 'k2', 'user', 'age', 'is_admin', 'salary']
#获取分区下is_admin的布尔值
res = cfg.getboolean('section1', 'is_admin')  #查看is_admin的布尔值
print(res)     #输出的是True
#获取分区下salary的浮点数
res = cfg.getfloat('section1', 'salary')  #查看浮点数
print(res)        #31.0
#获取分区下age选项的整型数字
res = cfg.getint('section1', 'age')     #查看整型
print(res)            #25  整型数字
#获取分区下所有键值对
res = cfg.items('section1')    #查看分区下所有选项的键值
print(res)   #[('k1','v1'),('k2','v2'),('user', 'ming'),('age', '25'),('is_admin', 'True'),('salary', '31')]
​
​
#2.改写
cfg = configparser.ConfigParser()  #创建配置文件解析器
cfg.read('test.cfg', encoding='utf-8')  #读取名为test的配置文件,编码格式为utf-8
#删除整个标题section2
config.remove_section('section2')
​
#删除标题section1下的某个k1和k2
config.remove_option('section1','k1')
config.remove_option('section1','k2')
​
#判断是否存在某个标题
print(config.has_section('section1'))
​
#判断标题section1下是否有user
print(config.has_option('section1',''))
​
​
#添加一个标题
config.add_section('egon')
​
#在标题egon下添加name=egon,age=18的配置
config.set('egon','name','egon')
config.set('egon','age',18) #报错,必须是字符串
!!!注意
#最后将修改的内容写入文件,完成最终的修改
config.write(open('a.cfg','w'))
原文地址:https://www.cnblogs.com/5j421/p/10098148.html