發現一個簡單而又強大的讀寫設定檔的lib,http://www.voidspace.org.uk/python/configobj.html。
個人覺得最大的亮點在於內建的格式校正功能,並且支援複雜的嵌套格式,而且使用起來也相當的簡便。
來看例子吧。
讀檔案
複製代碼 代碼如下:from configobj import ConfigObj
config = ConfigObj(filename)
#
value1 = config['keyword1']
value2 = config['keyword2']
#
section1 = config['section1']
value3 = section1['keyword3']
value4 = section1['keyword4']
#
# you could also write
value3 = config['section1']['keyword3']
value4 = config['section1']['keyword4']
寫檔案
複製代碼 代碼如下:from configobj import ConfigObj
config = ConfigObj()
config.filename = filename
#
config['keyword1'] = value1
config['keyword2'] = value2
#
config['section1'] = {}
config['section1']['keyword3'] = value3
config['section1']['keyword4'] = value4
#
section2 = {
'keyword5': value5,
'keyword6': value6,
'sub-section': {
'keyword7': value7
}
}
config['section2'] = section2
#
config['section3'] = {}
config['section3']['keyword 8'] = [value8, value9, value10]
config['section3']['keyword 9'] = [value11, value12, value13]
#
config.write()
更多內容請參閱下官方doc文檔。