Python使用configparser庫讀取配置文件
更新時間:2020年02月22日 15:07:11 作者:奔奔-武
這篇文章主要介紹了Python使用configparser庫讀取配置文件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
這篇文章主要介紹了Python使用configparser庫讀取配置文件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
背景:
在寫接口自動化框架,配置數(shù)據(jù)庫連接時,測試環(huán)境和UAT環(huán)境的連接信息不一致,這時可以將連接信息寫到conf或者cfg配置文件中
python環(huán)境請自行準備。
python代碼直接封裝成類,方便其他模塊的引入。
from configparser import ConfigParser class DoConfig: def __init__(self,filepath,encoding='utf-8'): self.cf = ConfigParser() self.cf.read(filepath,encoding) #獲取所有的section def get_sections(self): return self.cf.sections() #獲取某一section下的所有option def get_option(self,section): return self.cf.options(section) #獲取section、option下的某一項值-str值 def get_strValue(self,section,option): return self.cf.get(section,option) # 獲取section、option下的某一項值-int值 def get_intValue(self, section, option): return self.cf.getint(section, option) # 獲取section、option下的某一項值-float值 def get_floatValue(self, section, option): return self.cf.getfloat(section, option) # 獲取section、option下的某一項值-bool值 def get_boolValue(self, section, option): return self.cf.getboolean(section, option) def setdata(self,section,option,value): return self.cf.set(section,option,value) if __name__ == '__main__': cf = DoConfig('demo.conf') res = cf.get_sections() print(res) res = cf.get_option('db') print(res) res = cf.get_strValue('db','db_name') print(res) res = cf.get_intValue('db','db_port') print(res) res = cf.get_floatValue('user_info','salary') print(res) res = cf.get_boolValue('db','is') print(res) cf.setdata('db','db_port','3306') res = cf.get_strValue('db', 'db_port') print(res)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
基于python SMTP實現(xiàn)自動發(fā)送郵件教程解析
這篇文章主要介紹了基于python實現(xiàn)自動發(fā)送郵件教程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06Python3的urllib.parse常用函數(shù)小結(urlencode,quote,quote_plus,unquot
這篇文章主要介紹了Python3的urllib.parse常用函數(shù),結合實例形式分析了urlencode,quote,quote_plus,unquote,unquote_plus等函數(shù)的相關使用技巧,需要的朋友可以參考下2016-09-09