python读写配置文件

相关模块:ConfigParser模块

1、创建配置文件

在项目的configs目录线建立一个配置文件,命名为:test.ini

内容如下:

[baseconf]
host=127.0.0.1
port=3306
user=root
password=root
db_name=gloryroad
[test]
ip=127.0.0.1
int=1
float=1.5
bool=True

注意:要将文件保存为ansi编码,utf-8编码会报错

文件中的[baseconf]为section

2、读配置文件

import ConfigParser
cf=ConfigParser.ConfigParser()
cf.read(path) 读配置文件(ini、conf)返回结果是列表
cf.sections() 获取读到的所有sections(域),返回列表类型
cf.options('sectionname') 某个域下的所有key,返回列表类型
cf.items('sectionname') 某个域下的所有key,value对
value=cf.get('sectionname','key') 获取某个域下的key对应的value值
cf.type(value) 获取的value值的类型

(1)getint(section, option)

获取section中option的值,返回int类型数据,所以该函数只能读取int类型的值。

(2)getboolean(section, option)

获取section中option的值,返回布尔类型数据,所以该函数只能读取boolean类型的值。

(3)getfloat(section, option)

获取section中option的值,返回浮点类型数据,所以该函数只能读取浮点类型的值。

(4)has_option(section, option)

检测指定section下是否存在指定的option,如果存在返回True,否则返回False。

(5)has_section(section)

检测配置文件中是否存在指定的section,如果存在返回True,否则返回False。

3、动态写配置文件

cf.add_section('test') 添加一个域

cf.set('test3','key12','value12') 域下添加一个key value对

cf.write(open(path,'w')) 要使用'w'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微个日光日

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值