├── example.cfg ├── example.py └── readme.md /example.cfg: -------------------------------------------------------------------------------- 1 | [section1] 2 | var1 = test1 3 | var2 = 'test2' 4 | var3 = "test3" 5 | list1 = 1,2,3 6 | list2 = a,b,c 7 | list3 = 'a','b','c' 8 | 9 | [section2] 10 | var4 : test4 11 | var5 : 'test5' 12 | var6 : "test6" 13 | 14 | [section3] 15 | dict1 = {'key1':'val1', 'key2':'val2'} 16 | dict2 = {'key1':1, 'key2':2} 17 | dict3 = { 18 | 'key1':'val1', 19 | 'key2':'val2' 20 | } 21 | dict4 = { 22 | 'key1' : [2,3,'4'], 23 | 'key2' : 'c' 24 | } -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | from configparser import ConfigParser 2 | import ast 3 | 4 | config = ConfigParser() 5 | config.read('example.cfg') 6 | 7 | # single variables 8 | print(config.get('section1', 'var1')) 9 | print(config.get('section1', 'var2')) 10 | print(config.get('section1', 'var3')) 11 | 12 | print(config.get('section2', 'var4')) 13 | print(config.get('section2', 'var5')) 14 | print(config.get('section2', 'var6')) 15 | 16 | # lists 17 | l1 = config.get('section1', 'list1').split(',') 18 | l2 = config.get('section1', 'list2').split(',') 19 | l3 = map(lambda s: s.strip('\''), config.get('section1', 'list3').split(',')) 20 | 21 | print(l1,type(l1)) 22 | print(l2,type(l2)) 23 | print(l3,type(l3)) 24 | 25 | # dictionaries 26 | d1 = ast.literal_eval(config.get('section3', 'dict1')) 27 | print(d1, type(d1)) 28 | 29 | d2 = ast.literal_eval(config.get('section3', 'dict2')) 30 | print(d2, type(d2)) 31 | 32 | d3 = ast.literal_eval(config.get('section3', 'dict3')) 33 | print(d3, type(d3)) 34 | 35 | d4 = ast.literal_eval(config.get('section3', 'dict4')) 36 | print(d4, type(d4)) 37 | print(d4['key1'], type(d4['key1'])) 38 | print(d4['key1'][1], type(d4['key1'][1])) 39 | print(d4['key1'][2], type(d4['key1'][2])) 40 | 41 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ### Python ConfigParser Example 2 | 3 | This is some simple illustrative code for Python's ConfigParser module, written as I was trying to figure out how to store more complex data structures in config files. 4 | 5 | In addition to the normal stuff, such as getting a single variable/value from a config file, this code also illustrates how to configure and access complex data structures from your config files, such as 6 | 7 | * dicts 8 | * lists 9 | * nested data structures (e.g. lists within a dict) 10 | 11 | --------------------------------------------------------------------------------