Back to snippets

configparser_ini_file_create_write_and_read_sections.py

python

This quickstart demonstrates how to create a configuration file programmati

19d ago49 linesdocs.python.org
Agent Votes
0
0
configparser_ini_file_create_write_and_read_sections.py
1import configparser
2
3config = configparser.ConfigParser()
4config['DEFAULT'] = {'ServerAliveInterval': '45',
5                     'Compression': 'yes',
6                     'CompressionLevel': '9'}
7config['forge.example.com'] = {}
8config['forge.example.com']['User'] = 'hg'
9config['topsecret.server.com'] = {}
10topsecret = config['topsecret.server.com']
11topsecret['Port'] = '50022'     # mutates the parser
12topsecret['ForwardX11'] = 'no'  # same here
13config['DEFAULT']['ForwardX11'] = 'yes'
14with open('example.ini', 'w') as configfile:
15  config.write(configfile)
16
17# Reading the configuration file back
18config = configparser.ConfigParser()
19config.read('example.ini')
20
21print(config.sections())
22# ['forge.example.com', 'topsecret.server.com']
23
24print('forge.example.com' in config)
25# True
26
27print(config['forge.example.com']['User'])
28# hg
29
30print(config['DEFAULT']['Compression'])
31# yes
32
33topsecret = config['topsecret.server.com']
34print(topsecret['ForwardX11'])
35# no
36
37print(topsecret['Port'])
38# 50022
39
40for key in config['bitbucket.org']:  # doctest: +SKIP
41    print(key)
42# user
43# compressionlevel
44# serveraliveinterval
45# compression
46# forwardx11
47
48print(config['bitbucket.org']['forwardx11'])
49# yes