A configuration file (or config file) is a file used to configure the initial settings for some computer programs. In Python, using a configuration file can significantly simplify the management of settings and parameters for your scripts, especially in a complex software system.
Different file formats can be used for config files in Python, such as .ini, .json, .yaml and .cfg. In this article, we’ll explore how to use each of these formats and some modules in Python that facilitate the reading and writing of config files.
ConfigParser Module
ConfigParser is a built-in Python module for reading .ini-style configuration files. It provides a way of reading and writing data from and to .ini files, which are a standard for config files in Windows.
Example of Config File in .ini Format
[DEFAULT] server = localhost [web_server] host = 127.0.0.1 port = 80 [db_server] host = 127.0.0.1 port = 3306
How to Read the Config File
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
print(config['DEFAULT']['server']) # localhost
print(config['web_server']['host']) # 127.0.0.1
print(config['db_server']['port']) # 3306JSON
JSON files are another common format for config files, and Python’s json module makes it easy to read and write these files.
Example of Config File in .json Format
{
"server": "localhost",
"web_server": {
"host": "127.0.0.1",
"port": 80
},
"db_server": {
"host": "127.0.0.1",
"port": 3306
}
}How to Read the Config File
import json
with open('config.json', 'r') as f:
config = json.load(f)
print(config['server']) # localhost
print(config['web_server']['host']) # 127.0.0.1
print(config['db_server']['port']) # 3306YAML
YAML is a human-friendly data serialization standard and it’s often used for writing configuration files. You can use the PyYAML module to work with YAML files.
Example of Config File in .yaml Format
server: localhost web_server: host: 127.0.0.1 port: 80 db_server: host: 127.0.0.1 port: 3306
How to Read the Config File
import yaml
with open('config.yaml', 'r') as f:
config = yaml.safe_load(f)
print(config['server']) # localhost
print(config['web_server']['host']) # 127.0.0.1
print(config['db_server']['port']) # 3306Environment Variables
For sensitive data, like usernames and passwords, you may want to use environment variables instead of plain text configuration files. The os module in Python allows you to access these environment variables.
How to Set Environment Variables in Python
import os os.environ['USER'] = 'my_user' os.environ['PASSWORD'] = 'my_password'
How to Get Environment Variables in Python
import os
user = os.getenv('USER')
password = os.getenv('PASSWORD')
print(user) # my_user
print(password) # my_passwordIn conclusion, Python provides a variety of methods and modules to handle configuration files in different formats. This flexibility allows you to choose the best approach according to your project requirements, making your code more modular, secure, and easier to manage.