Python configparser模塊常用方法解析
ConfigParser模塊在python中用來讀取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一個或多個節(jié)(section), 每個節(jié)可以有多個參數(shù)(鍵=值)。使用的配置文件的好處就是不用在程序員寫死,可以使程序更靈活。
注意:在python 3 中ConfigParser模塊名已更名為configparser
configparser函數(shù)常用方法:
讀取配置文件:
read(filename) #讀取配置文件,直接讀取ini文件內(nèi)容
sections() #獲取ini文件內(nèi)所有的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類型
>>>>>獲取指定的section下的option <class 'str'> 127.0.0.1getint(section,option) 返回int類型
getfloat(section, option) 返回float類型
getboolean(section,option) 返回boolen類型
舉例如下:
配置文件ini如下:
[logging]
level = 20
path =
server =[mysql]
host=127.0.0.1
port=3306
user=root
password=123456
注意,也可以使用:替換=
代碼如下:
import configparser
from until.file_system import get_init_path
conf = configparser.ConfigParser()
file_path = get_init_path()
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)
運行結(jié)果如下:
file_path : /Users/xxx/Desktop/xxx/xxx/xxx.ini
獲取配置文件所有的section ['logging', 'mysql']
獲取指定section下所有option ['host', 'port', 'user', 'password']
獲取指定section下所有的鍵值對 [('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')]
獲取指定的section下的option <class 'str'> 127.0.0.1
綜合使用方法:
import configparser
"""
讀取配置文件信息
"""
class ConfigParser():
config_dic = {}
@classmethod
def get_config(cls, sector, item):
value = None
try:
value = cls.config_dic[sector][item]
except KeyError:
cf = configparser.ConfigParser()
cf.read('settings.ini', encoding='utf8') #注意setting.ini配置文件的路徑
value = cf.get(sector, item)
cls.config_dic = value
finally:
return value
if __name__ == '__main__':
con = ConfigParser()
res = con.get_config('logging', 'level')
print(res)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
音頻處理 windows10下python三方庫librosa安裝教程
這篇文章主要介紹了音頻處理 windows10下python三方庫librosa安裝方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
使用Matplotlib創(chuàng)建自定義可視化圖表的方法小結(jié)
Matplotlib 是 Python 中最流行的繪圖庫之一,它提供了豐富的功能和靈活性,使用戶能夠創(chuàng)建各種類型的可視化圖表,本文將介紹如何使用 Matplotlib 中的各種功能和技巧來創(chuàng)建自定義的可視化圖表,文中通過代碼示例講解的非常詳細,需要的朋友可以參考下2024-05-05
基于Python+Pygame實現(xiàn)變異狗大戰(zhàn)游戲
只有你想不到,沒有我找不到寫不了的好游戲!這篇文章就來和大家分享一下如何基于Python+Pygame實現(xiàn)變異狗大戰(zhàn)游戲,感興趣的可以了解一下2023-03-03

