栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python

前言

ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)

配置信息

读取配置文件:

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类型
演示

配置文件ini如下:

[logging]
level = 20
path =
server =

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

代码如下:

import configparser

conf = configparser.ConfigParser()
file_path = "txt.ini"
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)

运行结果:

  • file_path : txt.ini
  • 获取配置文件所有的section [‘logging’, ‘mysql’]
  • 获取指定section下所有option [‘host’, ‘port’, ‘user’, ‘password’]
  • 获取指定section下所有的键值对 [(‘host’, ‘127.0.0.1’), (‘port’, ‘3306’), (‘user’,
    ‘root’), (‘password’, ‘123456’)]
  • 获取指定的section下的option 127.0.0.1
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/341858.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号