Python 简单读取配置文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yk150915/article/details/82180744

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'>

猜你喜欢

转载自blog.csdn.net/yk150915/article/details/82180744