Python configparser模塊應(yīng)用過(guò)程解析
一、configparser模塊是什么
可以用來(lái)操作后綴為 .ini 的配置文件;
python標(biāo)準(zhǔn)庫(kù)(就是python自帶的意思,無(wú)需安裝)
二、configparser模塊基本使用
2.1 讀取 ini 配置文件
#存在 config.ini 配置文件,內(nèi)容如下:[DEFAULT]excel_path = ../test_cases/case_data.xlsxlog_path = ../logs/test.loglog_level = 1[email]user_name = 32@qq.compassword = 123456
使用configparser模塊讀取配置文件
import configparser#創(chuàng)建配置文件對(duì)象conf = configparser.ConfigParser()#讀取配置文件conf.read(’config.ini’, encoding='utf-8')#列表方式返回配置文件所有的sectionprint( conf.sections() ) #結(jié)果:[’default’, ’email’]#列表方式返回配置文件email 這個(gè)section下的所有鍵名稱print( conf.options(’email’) ) #結(jié)果:[’user_name’, ’password’]#以[(),()]格式返回 email 這個(gè)section下的所有鍵值對(duì)print( conf.items(’email’) ) #結(jié)果:[(’user_name’, ’32@qq.com’), (’password’, ’123456’)]#使用get方法獲取配置文件具體的值,get方法:參數(shù)1-->section(節(jié)) 參數(shù)2-->key(鍵名)value = conf.get(’default’, ’excel_path’)print(value)
2.2 寫(xiě)入 ini 配置文件(字典形式)
import configparser#創(chuàng)建配置文件對(duì)象conf = configparser.ConfigParser()#’DEFAULT’為section的名稱,值中的字典為section下的鍵值對(duì)conf['DEFAULT'] = {’excel_path’ : ’../test_cases/case_data.xlsx’ , ’log_path’ : ’../logs/test.log’}conf['email'] = {’user_name’:’32@qq.com’,’password’:’123456’}#把設(shè)置的conf對(duì)象內(nèi)容寫(xiě)入config.ini文件with open(’config.ini’, ’w’) as configfile: conf.write(configfile)
2.3 寫(xiě)入 ini 配置文件(方法形式)
import configparser#創(chuàng)建配置文件對(duì)象conf = configparser.ConfigParser()#讀取配置文件conf.read(’config.ini’, encoding='utf-8')#在conf對(duì)象中新增sectionconf.add_section(’webserver’)#在section對(duì)象中新增鍵值對(duì)conf.set(’webserver’,’ip’,’127.0.0.1’)conf.set(’webserver’,’port’,’80’)#修改’DEFAULT’中鍵為’log_path’的值,如沒(méi)有該鍵,則新建conf.set(’DEFAULT’,’log_path’,’test.log’)#刪除指定sectionconf.remove_section(’email’)#刪除指定鍵值對(duì)conf.remove_option(’DEFAULT’,’excel_path’)#寫(xiě)入config.ini文件with open(’config.ini’, ’w’) as f: conf.write(f)
上述3個(gè)例子基本闡述了configparser模塊的核心功能項(xiàng);
例1中,encoding='utf-8'為了放置讀取的適合中文亂碼; 例2你可以理解為在字典中新增數(shù)據(jù),鍵:配置文件的section,字符串格式;值:section的鍵值對(duì),字典格式; 例3中在使用add_section方法時(shí),如果配置文件存在section,則會(huì)報(bào)錯(cuò);而set方法在使用時(shí),有則修改,無(wú)則新建。以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項(xiàng)目的過(guò)程2. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過(guò)程解析3. SharePoint Server 2019新特性介紹4. ASP中常用的22個(gè)FSO文件操作函數(shù)整理5. 三個(gè)不常見(jiàn)的 HTML5 實(shí)用新特性簡(jiǎn)介6. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp7. .Net core 的熱插拔機(jī)制的深入探索及卸載問(wèn)題求救指南8. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)9. 讀大數(shù)據(jù)量的XML文件的讀取問(wèn)題10. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯(cuò)誤頁(yè)的問(wèn)題
