Python的配置文件,,一. 什么是配置文件
Python的配置文件,,一. 什么是配置文件
一. 什么是配置文件?为什么要做配置文件?
将所有的代码和配置都变成模块化可配置化,这样就提高了代码的重用性,不再每次都去修改代码内部,这个就是我们逐步要做的事情,可配置化
二. 配置文件长啥样?
配置文件常见类型分为ini conf xml cfg,没啥区别,拍脑袋选用conf
文件内容结构为
section
? item
? option = value
[mysql_db_test]host = localhostport = 3306db = mysqluser = rootpasswd = 123456bool = True[key_word]key1 = please
二. python中的ConfigParser类
模块:from configparser import ConfigParser
configparser是Python自带的模块,用法如下:
创建ConfigParser对象。并调用read()函数打开配置文件,里面填的参数是地址
配置文件的格式是:[]包含的叫section,section下有option=value这样的键值
常用配置函数如下
sections() 得到所有的section,并以列表的形式返回
options(section) 得到该section的所有option (key值)
items(section) 得到该section的所有键值对
get(section, option) 得到section中option的值,返回为string类型,指定标签下面的key对应的value值
getint(section, option) 返回为int类型
getintfloat(section, option) 返回为float类型
getintbool(section, option) 返回为boolean类型
add_section() 往配置文件中添加section
set(section, option, value) 在section下设置option=value,如果option存在则会覆盖
cp.write(open(‘db.conf‘,‘w‘)) 将新增的配置信息写入到文件中
from configparser import ConfigParsercf = ConfigParser()cf.read(‘db.conf‘)#获取所有section,返回值为listsecs = cf.sections()print(secs)#获取db中的所有属性名option=cf.options(‘db‘)print(dboption)#获取db中的键值对item=cf.items(‘db‘)print(item)#获取section为db,属性名为db_pass的值value=cf.get(‘db‘,‘db_pass‘)print(value)#写配置文件cf.add_section(‘key_word‘)cf.set(‘key_word‘, ‘key‘, ‘value‘)cf.write(open(‘db.conf‘, ‘w‘))
Python的配置文件
评论关闭