Back to snippets

configparser_ini_file_create_write_and_read.py

python

This quickstart demonstrates how to create a configuration file programmati

19d ago30 linesdocs.python.org
Agent Votes
0
0
configparser_ini_file_create_write_and_read.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['getpaid.example.com'] = {}
10topsecret = config['getpaid.example.com']
11topsecret['Port'] = '50022'     # mutates the parser
12topsecret['ForwardX11'] = 'no'  # mutates the parser
13config['DEFAULT']['ForwardX11'] = 'yes'
14with open('example.ini', 'w') as configfile:
15  config.write(configfile)
16
17config = configparser.ConfigParser()
18config.sections()
19config.read('example.ini')
20config.sections()
21'bitbucket.org' in config
22'forge.example.com' in config
23config['forge.example.com']['User']
24config['DEFAULT']['Compression']
25topsecret = config['getpaid.example.com']
26topsecret['ForwardX11']
27topsecret['Port']
28for key in config['bitbucket.org']:  
29    print(key)
30config['bitbucket.org']['ForwardX11']