Python 簡單讀取配置檔案
阿新 • • 發佈:2019-01-13
configparser 是 Pyhton 標準庫中用來解析配置檔案的模組,並且內建方法和字典非常接近。Python2.x 中名為 ConfigParser,3.x 已更名小寫,並加入了一些新功能。
本文使用configparser模組簡單讀取配置檔案,如字串、列表、字典值的讀取:
原始碼示例,使用python2.x:
import ConfigParser
import ast
config = ConfigParser.RawConfigParser()
config.read('example.cfg')
# single variables
print type (config.get('section1', 'var1'))
print type(config.get('section1', 'var2'))
print type(config.get('section1', 'var3'))
print type(config.get('section2', 'var4'))
print config.get('section2', 'var5')
print config.get('section2', 'var6')
# lists
l1 = config.get('section1', 'list1').split(',')
l2 = config.get('section1' , 'list2').split(',')
l3 = map(lambda s: s.strip('\''), config.get('section1', 'list3').split(','))
print l1,type(l1)
print l2,type(l2)
print l3,type(l3)
# dictionaries
d1 = ast.literal_eval(config.get('section3', 'dict1'))
print d1, type(d1)
d2 = ast.literal_eval(config.get('section3', 'dict2'))
print d2, type(d2)
d3 = ast.literal_eval(config.get('section3', 'dict3'))
print d3, type(d3)
d4 = ast.literal_eval(config.get('section3', 'dict4'))
print d4, type(d4)
print d4['key1'], type(d4['key1'])
print d4['key1'][1], type(d4['key1'][1])
print d4['key1'][2], type(d4['key1'][2])
配置檔案如下:
[section1]
var1 = test1
var2 = 'test2'
var3 = "test3"
list1 = 1,2,3
list2 = a,b,c
list3 = 'a','b','c'
[section2]
var4 : test4
var5 : 'test5'
var6 : "test6"
[section3]
dict1 = {'key1':'val1', 'key2':'val2'}
dict2 = {'key1':1, 'key2':2}
dict3 = {
'key1':'val1',
'key2':'val2'
}
dict4 = {
'key1' : [2,3,'4'],
'key2' : 'c'
}
執行結果如下:
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
'test5'
"test6"
['1', '2', '3'] <type 'list'>
['a', 'b', 'c'] <type 'list'>
['a', 'b', 'c'] <type 'list'>
{'key2': 'val2', 'key1': 'val1'} <type 'dict'>
{'key2': 2, 'key1': 1} <type 'dict'>
{'key2': 'val2', 'key1': 'val1'} <type 'dict'>
{'key2': 'c', 'key1': [2, 3, '4']} <type 'dict'>
[2, 3, '4'] <type 'list'>
3 <type 'int'>
4 <type 'str'>