读取 ini 配置文件

ini 配置文件格式:db_config.ini

'''
[section]
option=value
'''
[DATABASE1]
host=192.168.30.80
port=3306
user=testacc
passwd=test1234
db=testdb
charset=utf_8

[DATABASE2]
host=192.168.30.80
port=3306

(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.4Interfacedb_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.4Interfacedb_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)
原文地址:https://www.cnblogs.com/cxx1/p/8677800.html