Config Files in Python
Config Files in Python
Configuration files are well suited to specify configuration data to your program. Within each config
file, values are grouped into different sections (e.g., “installation”, “debug” and “server”).
Each section then has a specific value for various variables in that section. For the same purpose,
there are some prominent differences between a config file and using a Python source file.
SAMPLE_CONFIG.TXT
[config]
option1=a
option2=b
option3=c
parser = configparser.ConfigParser()
parser.read("sample_config.txt")
print(parser.get("config", "option1"))
OUTPUT
a
print(parser.get("config", "option2"))
OUTPUT
b
print(parser.get("config", "option3"))
OUTPUT
c
Read configuration files written in the common .ini configuration file format.
Code #1 : Configuration File
abc.ini
[server]
nworkers: 32
port: 8080
root = /www/root
signature:
configur = ConfigParser()
print (configur.read('config.ini'))
One can also modify the configuration and write it back to a file using the cfg.write() method.
Code #3 :
configur.set('server','port','9000')
configur.set('debug','log_errors','False')
import sys
configur.write(sys.stdout)
Output :
[installation]
library = %(prefix)s/lib
include = %(prefix)s/include
bin = %(prefix)s/bin
prefix = /usr/local
[debug]
log_errors = False
show_warnings = False
[server]
port = 9000
nworkers = 32
pid-file = /tmp/spam.pid
root = /www/root
Names used in a config file are also assumed to be case-insensitive as shown in the code
below –
configur.get('installation','PREFIX')
configur.get('installation','prefix')
Output :
'/usr/local'
'/usr/local'
Multiple configuration files can be read together and their results can be merged into a
single configuration using ConfigParser, which makes it so special to use.
Example – A user made their own configuration file that looks as.
; ~/.config.ini
[installation]
prefix = /Users/beazley/test
[debug]
log_errors = False
This file can be merged with the previous configuration by reading it separately
Code #4 :
import os
# Previously read configuration
print (configur.get('installation', 'prefix'))