Python內(nèi)置模塊ConfigParser實現(xiàn)配置讀寫功能的方法
本文實例講述了Python內(nèi)置模塊ConfigParser實現(xiàn)配置讀寫功能的方法。分享給大家供大家參考,具體如下:
用于對特定的配置進行操作,當(dāng)前模塊的名稱在 python 3.x 版本中變更為 configparser。
#配置文件test.cfg [section1] k1 = v1 k2 :v2 k3 = 1 [section2] k1 = v1
#coding:utf-8 import ConfigParser config = ConfigParser.ConfigParser() config.read('test.cfg') # ########## 讀 ########## #獲取所有sections. secs = config.sections() print secs #['section1', 'section2'] #獲取制定section的鍵key options = config.options('section1') print options #['k1', 'k2', 'k3'] #獲取指定section的鍵值對key-value item_list = config.items('section1') print item_list #[('k1', 'v1'), ('k2', 'v2'), ('k3', '1')] #獲取指定key的value # 獲取字符串類型的value val1 = config.get('section1','k1') # 獲取整型的value val2 = config.getint('section1','k3') # ########## 增改刪 ########## # 增加section if not config.has_section('section3'): config.add_section('section3') config.write(open('test.cfg', "w")) #設(shè)置option if not config.has_section('section3'): config.set('section3','k1',11111) config.write(open('test.cfg', "w")) # 移除option ret = config.remove_option('section3','k1') print ret #True or False config.write(open('test.cfg', "w")) # 移除section ret = config.remove_section('section3') print ret #True or False config.write(open('test.cfg', "w"))
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python中g(shù)lobal關(guān)鍵字的用法詳解
Python是一種簡單而強大的編程語言,提供了許多功能和語法來幫助開發(fā)人員編寫高效的代碼,其中一個常用的功能是使用global關(guān)鍵字來在函數(shù)內(nèi)部訪問和修改全局變量,在本文中,我們將深入探討Python中g(shù)lobal關(guān)鍵字的用法,以及使用它的一些最佳實踐2023-12-12用python + openpyxl處理excel2007文檔思路以及心得
最近要幫做RA的老姐寫個合并excel工作表的腳本……源數(shù)據(jù)是4000+個excel 工作表,分布在9個xlsm文件里,文件內(nèi)容是中英文混雜的一些數(shù)據(jù),需要從每張表中提取需要的部分,分門別類合并到多個大的表里。2014-07-07