读取 ini 配置文件
2024-09-11 09:30:11
ini 配置文件格式:db_config.ini
'''
[section]
option=value
'''
[DATABASE1]
host=192.168.30.80
port=
user=testacc
passwd=test1234
db=testdb
charset=utf_8 [DATABASE2]
host=192.168.30.80
port=
(1)首先安装 configparser 类:一般标准库中都自带的,若无,则可 直接运行 pip install configparser
(2)使用这个类读取文件
基本会使用到的一些函数: -read(filename) 直接读取文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option,并以列表的形式返回
-items(section) 得到该section的所有键值对,并以列表的形式返回
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。
#简单的读取
from configparser import ConfigParser conf=ConfigParser()
conf.read('E:\PyCharm 2017.2.4\Interface\db_config.ini')
print(conf.sections())
print(conf.options('DATABASE1'))
print(conf.items('DATABASE1')) #输出结果
['DATABASE1', 'DATABASE2']
['host', 'port', 'user', 'passwd', 'db', 'charset']
[('host', '192.168.30.80'), ('port', '3306'), ('user', 'testacc'), ('passwd', 'test1234'), ('db', 'testdb'), ('charset', 'utf_8')]
#进行了简单的封装,其他地方可进行引用
#read_db_conig.py
from configparser import ConfigParser file='E:\PyCharm 2017.2.4\Interface\db_config.ini'
conf=ConfigParser()
conf.read(file) def getHostValue():
host= conf.get('DATABASE1', 'host')
return host
def getPortValue():
port=conf.get('DATABASE1','port')
return port
if __name__=='__main__':
host=getHostValue()
print(host)
最新文章
- ABP框架详解(六)Aspects
- spark的环境安装
- JS中的自执行函数
- NOIP2000 乘积最大
- cocos2d-x Loading界面实现资源加载
- iOS多线程篇:NSThread简单介绍和使用
- flask-bootstrap学习笔记
- 2015沈阳站-Meeting 最短路
- Xorboot-UEFI新手入门教程
- [CF286E] Ladies' shop
- Oracle亿级数据查询处理(数据库分表、分区实战)
- 第一行代码 3-5 软件也要拼脸蛋-UI界面-更强大的滚动条- 聊天室
- 转 Oracle监听器启动出错:本地计算机上的OracleOraDb11g_home1TNSListener服务启动后又停止了解决方案
- MySQL5.7 常用用户操作
- eclipse Git配置
- js对象注意
- Java中的文件和stream流的操作代码
- Linux命令之kill
- CodeForces 879D Teams Formation
- javascript解析机制——预解析