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

读取.ini 配置文件configparser.ConfigParser()

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

读取.ini 配置文件configparser.ConfigParser()

一、配置文件

config.ini配置文件内容:
[log]
name=test_配置化
level=INFO
file_name=py30.log
file_ok=False
num=1

[MYSQL]
usr=nmb
passwd=123456

二、测试 读取config_ini配置文件.py

#读取配置数据.ini (ConfigParse类,自带的 在lib下configparser.py),学习代码如下:
import configparser
#实例化对象
conf = configparser.ConfigParser()
#读取配置文件 》返回列表,加载到内存中
read_ok=conf.read(“config.ini”,encoding=“utf-8”)

print(read_ok) #[‘config.ini’] 读取某一个配置 ,通过实例化对象.get(section,option)

value=conf.get(“log”,“name”)
print(value) #test_配置化

扩展

#-sections得到所有的section,并以列表的形式返回
print(conf.sections()) #[‘log’, ‘MYSQL’]

得到某section下的所有option的 key列表

print(conf.options(‘log’)) #[‘name’, ‘level’, ‘file_name’, ‘file_ok’]

-items(section)得到该section的所有键值对

print(conf.items(‘log’)) #[(‘name’, ‘test_配置化’), (‘level’, ‘INFO’), (‘file_name’, ‘py30.log’), (‘file_ok’, ‘false’)]

-get(section,option)得到section中option的值,返回为string类型

print(conf.get(‘log’,‘name’)) #test_配置化

-getint(section,option)得到section中的option的值,返回为int类型 ,配置的要与得到的像才行

print(conf.getint(‘log’,‘num’)) #1

-getboolean(section,option)得到section中的option的值,返回为int类型 ,配置的要与得到的像才行

print(conf.getboolean(‘log’,‘file_ok’)) #False

“”"
首先得到配置文件的所有分组section,然后根据分组逐一展示所有key-value
“”"
for section in conf.sections():
print(“section={}”.format(section))
for item in conf.items(section):
print(item,end=" ")
print()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/948048.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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