標籤:輸入 python bin parse class 有一個 div getpath sql
config.ini檔案的結構是以下這樣的:結構是"[ ]"之下是一個section,一部分一部分的結構。以下有三個section,分別為section0,section1,section2
[mysql config]host=127.0.0.1port=8080username=rootpassword=123456[online config]online=www.online.comusername=peixmpassword=123qwe[test config]test=www.test.comusername=peixmpassword=123qwe
那麼,怎麼在代碼中擷取到這些內容呢?
首先,要有一個config.ini檔案
#!/usr/bin/env/python# -*-coding:utf-8-*-# authour:xiapmin_peiimport configparser,os#封裝一個路徑,直接輸入檔案名稱filename就可以獲得filename的路徑def getPath(filename): return os.path.join(os.path.dirname(__file__),os.pardir,‘data‘,filename)class Config(object): def __init__(self,filename,section): """ :param filename: 檔案名稱 :param section: 屬於檔案中的第幾個section,這是整形 """ self.section = section #執行個體化一個configparser對象 self.cf = configparser.ConfigParser() #讀取檔案的內容 self.cf.read(getPath(filename)) def getconfig(self,avg): """ 獲得想要屬性的內容 :param avg: 屬性名稱 :return: 屬性的值 """ print self.cf.sections() parameter =self.cf.get(self.cf.sections()[self.section],avg) return parameterif __name__=="__main__": #執行個體化Config,想要config.ini檔案,第2個section的內容 con = Config("config.ini",1) #擷取online這個屬性的值 print con.getconfig(‘online‘)
執行結果:由此可見,sections是一個列表
[‘mysql config‘, ‘online config‘, ‘test config‘]
www.online.com
Process finished with exit code 0
python config.ini的應用