Pythonconfigparser模塊有哪些常用方法-創(chuàng)新互聯(lián)

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

成都創(chuàng)新互聯(lián)公司擁有一支富有激情的企業(yè)網(wǎng)站制作團隊,在互聯(lián)網(wǎng)網(wǎng)站建設(shè)行業(yè)深耕十余年,專業(yè)且經(jīng)驗豐富。十余年網(wǎng)站優(yōu)化營銷經(jīng)驗,我們已為上1000家中小企業(yè)提供了網(wǎng)站設(shè)計、成都網(wǎng)站建設(shè)解決方案,按需網(wǎng)站建設(shè),設(shè)計滿意,售后服務(wù)無憂。所有客戶皆提供一年免費網(wǎng)站維護!

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.1

getint(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)

當前標題:Pythonconfigparser模塊有哪些常用方法-創(chuàng)新互聯(lián)
文章出自:http://bm7419.com/article12/igsgc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、微信公眾號、做網(wǎng)站、定制開發(fā)、網(wǎng)站營銷網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司