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)

最新文章

  1. ABP框架详解(六)Aspects
  2. spark的环境安装
  3. JS中的自执行函数
  4. NOIP2000 乘积最大
  5. cocos2d-x Loading界面实现资源加载
  6. iOS多线程篇:NSThread简单介绍和使用
  7. flask-bootstrap学习笔记
  8. 2015沈阳站-Meeting 最短路
  9. Xorboot-UEFI新手入门教程
  10. [CF286E] Ladies' shop
  11. Oracle亿级数据查询处理(数据库分表、分区实战)
  12. 第一行代码 3-5 软件也要拼脸蛋-UI界面-更强大的滚动条- 聊天室
  13. 转 Oracle监听器启动出错:本地计算机上的OracleOraDb11g_home1TNSListener服务启动后又停止了解决方案
  14. MySQL5.7 常用用户操作
  15. eclipse Git配置
  16. js对象注意
  17. Java中的文件和stream流的操作代码
  18. Linux命令之kill
  19. CodeForces 879D Teams Formation
  20. javascript解析机制——预解析

热门文章

  1. LeetCode刷题-005最长回文子串
  2. L1-Day15
  3. Learning Feature Pyramids for Human Pose Estimation(理解)
  4. 第十七节,OpenCV(学习六)图像轮廓检测
  5. Mac环境下Vagrant的安装
  6. Sql server2012转sql server2008步骤经验总结(转)
  7. db2数据库备份与恢复
  8. webstorm Terminal 位置错乱解决方案
  9. Python-数据类型之元组
  10. SEH exception with code 0xc0000005 thrown in the test body