新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Pythonconfigparser模块有哪些常用方法-创新互联

小编这次要给大家分享的是Python configparser模块有哪些常用方法,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

成都创新互联公司拥有一支富有激情的企业网站制作团队,在互联网网站建设行业深耕十余年,专业且经验丰富。十余年网站优化营销经验,我们已为上1000家中小企业提供了网站设计、成都网站建设解决方案,按需网站建设,设计满意,售后服务无忧。所有客户皆提供一年免费网站维护!

ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用在程序员写死,可以使程序更灵活。

注意:在python 3 中ConfigParser模块名已更名为configparser

configparser函数常用方法:

读取配置文件:

read(filename) #读取配置文件,直接读取ini文件内容

sections() #获取ini文件内所有的section,以列表形式返回['logging', 'mysql']

options(sections) #获取指定sections下所有options ,以列表形式返回['host', 'port', 'user', 'password']

items(sections) #获取指定section下所有的键值对,[('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')]

get(section, option) #获取section中option的值,返回为string类型
>>>>>获取指定的section下的option 127.0.0.1

getint(section,option) 返回int类型
getfloat(section, option) 返回float类型
getboolean(section,option) 返回boolen类型

举例如下:

配置文件ini如下:

[logging]
level = 20
path =
server =

[mysql]
host=127.0.0.1
port=3306
user=root
password=123456

注意,也可以使用:替换=

代码如下:

import configparser
from until.file_system import get_init_path

conf = configparser.ConfigParser()
file_path = get_init_path()
print('file_path :',file_path)
conf.read(file_path)

sections = conf.sections()
print('获取配置文件所有的section', sections)

options = conf.options('mysql')
print('获取指定section下所有option', options)


items = conf.items('mysql')
print('获取指定section下所有的键值对', items)


value = conf.get('mysql', 'host')
print('获取指定的section下的option', type(value), value)

本文标题:Pythonconfigparser模块有哪些常用方法-创新互联
分享路径:http://www.wjwzjz.com/article/igsgc.html
在线咨询
服务热线
服务热线:028-86922220
TOP