config.ini文件的結構是以下這樣的:結構是"[ ]"之下是一個section,一部分一部分的結構。以下有三個section,分別為section0,section1,section2
[mysql config] host=127.0.0.1 port=8080 username=root password=123456 [online config] online=www.online.com username=peixm password=123qwe [test config] test=www.test.com username=peixm password=123qwe
那么,怎么在代碼中獲取到這些內容呢?
首先,要有一個config.ini文件,我的目錄結構是以下這樣:
#!/usr/bin/env/python # -*-coding:utf-8-*- # authour:xiapmin_pei import 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 parameter if __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