· 5 years ago · Jan 19, 2020, 09:02 AM
1#config_parser_write.py
2
3from configparser import ConfigParser
4
5conf = ConfigParser()
6
7conf['settings'] = {
8 'debug': 'true',
9 'secret_key': 'abc123',
10 'log_path': '/myapp/app.log',
11 'image_path': '/myapp/images'
12}
13
14conf['db'] = {
15 'db_name': 'my_db',
16 'db_host': 'localhost',
17 'db_port': '8889'
18}
19
20conf['files'] = {
21 'use_cdn': 'false',
22 'image_file': '${settings:image_path}/files'
23}
24
25with open('./config_parser.cfg','w') as f:
26 conf.write(f)
27
28
29#config_parser_read.py
30
31from configparser import ConfigParser, ExtendedInterpolation
32
33parser = ConfigParser(interpolation=ExtendedInterpolation())
34parser.read('./config_parser.cfg')
35
36print(parser.sections())
37print(parser.options('db'))
38
39print('db' in parser)
40print(parser.get('db','db_name'))
41print(parser.getint('db','db_port'))
42print(parser.get('db','db_size',fallback='500gb'))
43
44print(parser.get('files','image_file'))
45
46#config_parser.cfg
47
48[settings]
49debug = true
50secret_key = abc123
51log_path = /myapp/app.log
52image_path = /myapp/images
53
54[db]
55db_name = my_db
56db_host = localhost
57db_port = 8889
58
59[files]
60use_cdn = false
61image_file = ${settings:image_path}/files