小編這次要給大家分享的是Python configparser模塊有哪些常用方法,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。

ConfigParser模塊在python中用來讀取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一個(gè)或多個(gè)節(jié)(section), 每個(gè)節(jié)可以有多個(gè)參數(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下所有的鍵值對(duì),[('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下所有的鍵值對(duì)', items)
value = conf.get('mysql', 'host')
print('獲取指定的section下的option', type(value), value)            
                當(dāng)前標(biāo)題:Pythonconfigparser模塊有哪些常用方法-創(chuàng)新互聯(lián)
                
                文章出自:http://www.chinadenli.net/article12/igsgc.html
            
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、微信公眾號(hào)、做網(wǎng)站、定制開發(fā)、網(wǎng)站營(yíng)銷、網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容
