Python模塊之: ConfigParser 配置文件讀取 Python模塊之: ConfigParser 配置文件讀取

Python模塊之: ConfigParser 配置文件讀取

 

ConfigParser用於讀寫相似INI文件的配置文件,配置文件的內容可組織爲組,還支持多個選項值(option-value)類型。html

ConfigParser使用用的配置文件格式由一個或多個命名的節(section)組成,每一節包含由key和value構成的選項(option)。post

在一節中每行列出一個選項。行以選項名開頭,選項名與值之間用一個冒號(:)或一個等號(=)分開。url

1.讀取配置文件spa

-read(filename) 直接讀取ini文件內容
-sections() 獲得全部的section,並以列表的形式返回
-options(section) 獲得該section的全部option
-items(section) 獲得該section的全部鍵值對
-get(section,option) 獲得section中option的值,返回爲string類型
-getint(section,option) 獲得section中option的值,返回爲int類型
 
2.寫入配置文件
-add_section(section) 添加一個新的section
-set( section, option, value) 對section中的option進行設置
須要調用write將內容寫入配置文件。
 
示例
test.conf
[sec_a]
a_key1 = 20
a_key2 = 10
 
[sec_b]
b_key1 = 121
b_key2 = b_value2
b_key3 = $r
b_key4 = 127.0.0.1
 
getConfig.py
複製代碼
import ConfigParser

 

cf = ConfigParser.ConfigParser()

#allow_no_value=True參數能夠容許配置文件的選項中只有key而沒有value #read config cf.read("test.conf")
#read能夠設置讀取多個配置文件,使用列表形式便可 # return all section secs = cf.sections() print 'sections:', secs opts = cf.options("sec_a") print 'options:', opts kvs = cf.items("sec_a") print 'sec_a:', kvs #read by type str_val = cf.get("sec_a", "a_key1") int_val = cf.getint("sec_a", "a_key2") print "value for sec_a's a_key1:", str_val print "value for sec_a's a_key2:", int_val #write config #update value cf.set("sec_b", "b_key3", "new-$r") #set a new value cf.set("sec_b", "b_newkey", "new-value") #create a new section cf.add_section('a_new_section') cf.set('a_new_section', 'new_key', 'new_value') #write back to configure file cf.write(open("test.conf", "w"))
複製代碼
相關文章
相關標籤/搜索