configparser是python中自带的一个配置文件读写的库,,python2中为ConfigParser在python3中更名为configparser
导入模块:import configparser
读取配置用法:
1)创建configparser对象,并调用read(filename)函数打开配置文件,里面填的参数是地址。
2)常用配置函数如下:
sections() 得到所有的section,并以列表的形式返回
options(section) 得到该section的所有option(key值)
items(section) 得到该section的所有键值对
get(section,option) 得到section中option的值,返回为string类型,指定标签下面的key对应的value值
getint(section,option) 得到section中option的值,返回为int类型
举个例子:
文件名:class_6.conf(配置信息)
[mysql]
db_host=localhost
db_port=3306
db_user=root
db_pass=root
name=teacher
[HTTP]
host=https://graph.qq.com
port=443
文件名:class_6_read.py(读取配置文件)
'''配置文件的使用'''
import configparser#引入这个类
#1.函数的具体用法
#1.read 打开配置文件
cf=configparser.ConfigParser()#创建一个对象
cf.read("class_6.conf")
#2.sections()返回数据片段,比如说这个标签[mysql]
s=cf.sections()
print("返回的配置文件如下",s)
#3.options(sections)返回指定的片段里面的所有options
name=cf.options("mysql")
print("options(sectdions)的用法",name)
# #4.items(section)返回指定片段里面所有的key&value
value=cf.items("mysql")
print("返回的items值:",value)
# #5.返回片段里面具体数据get(section,option),返回值类是string
db_host=cf.get("mysql","db_host")
db_port=cf.get("mysql","db_port")
db_user=cf.get("mysql","db_user")
db_pass=cf.get("mysql","db_pass")
print("主机地址是:",db_host)
print("端口是:",db_port)
print("用户名是:",db_user)
print("密码是:",db_pass)
#6.getint()返回值类型是int
'''这里就不强调,你们知道这个用法就好'''
#7.读取配置的另一个用法
db_host2=cf["mysql"]["db_host"]
print("主机地址是:",db_host2)
写入配置用法:
add_section(new_section_name):新建一个section,如果已存在会报错。
set(section_name, option_name, value): 如果option_name存在则更新value,如果不存在则新建一个option和value,但是如果section不存在会报错。
write()方法将内容重新写入到文件中,需要注意的是如果在写之前没有读去过这个文件那么这次写入将会导致之前的文件内容被覆盖掉。
举个例子:
import configparser
cf.add_section("section1")
cf.set('section1', 'key1', 'value1')
cf.write(open("class_6.conf", 'w'))
print(cf.sections())
print(cf.items("section1"))
删除配置操作:
remove_option(section_name,option_name):删除指定的option,section不存在会报错。
remove_section(section_name):删除指定的section。
需要注意这里的删除仅仅只是在内存中进行的,还要进行write()操作写入到文件中,否则配置文件实际上是没有被更改的。
import configparser
cf.remove_option("section1", "key1")
print(cf.sections())
print(cf.items("section1"))
cf.remove_section("section1")
cf.write(open("class_6.conf", 'w'))