当前位置: 首页 > 图灵资讯 > 行业资讯> python的配置文件怎样写?

python的配置文件怎样写?

发布时间:2025-12-31 17:00:04

创建配置文件

在D盘中建立配置文件,名称为: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

二、阅读配置文件

import ConfigParser

cf=ConfigParser.ConfigParser()

cf.read(path) 读配置文件(ini、conf)返回结果是列表

cf.sections() 获取所有读取的sections(域),并返回列表类型

cf.options('sectionname') 所有key在某个域下返回列表类型

cf.items('sectionname') value对某个域下的所有key

value=cf.get('sectionname','key') 获取某个yu下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。

三、动态编写配置文件

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

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

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

learn to fail, failure to learn

更多Python知识请关注Python自学网

相关文章

python的配置文件怎样写?

python的配置文件怎样写?

2025-12-31
python怎么判断数字不等?

python怎么判断数字不等?

2025-12-31
文本处理用c还是用python

文本处理用c还是用python

2025-12-31
python实现报表用什么?

python实现报表用什么?

2025-12-31
python web.py乱码怎么解决?

python web.py乱码怎么解决?

2025-12-30
python udp不能接收数据怎么解决?

python udp不能接收数据怎么解决?

2025-12-30