Python Examples
Convert IP to Integer and Integer To IP in Python How to Get IPv4/IPv6 Address Range from CIDR in Python? Compare Two Objects For Equality in Python How to find Duplicate Elements from a List in Python Convert Timestamp to datetime in Python Convert datetime to Timestamp in Python Generate Random String of Specific Length in Python Encryption and Decryption of Strings in Python The string module in Python Convert string to bytes in Python Convert bytes to string in Python Convert string to datetime and datetime to string in Python Call a function Asynchronously from within a Loop and wait for the Results in Python Remove Duplicate Elements from a List in Python Caching in Python with Examples How to Bulk Insert and Retrieve Data from Redis in Python How to Write Unit Test in Python Read and Write CSV Files in Python Read and Write Data to a Text File in Python How to Convert CSV to JSON in Python Create ICS Calendar File in Python Install Python on Windows 10/11 Install Python on Ubuntu 20.04 or 22.04.3 Python - Install Virtual Environment How to Find a Specific Field Value from a JSON list in Python Download and Unzip a Zipped File in Python Python Install PIP Python Install Virtual Environment How to Fix Python Error: string argument without an encoding Compare Two JSON files in Python How to Hash a Dictionary Object in Python? Create a Digital Clock in Python Create Multiple URLs Using Each Path of a URL in Python Send an Email with Multiple Attachments using Amazon SES in Python SQLAlchemy Query Examples for Effective Database Management SQLAlchemy Query to Find IP Addresses from an IP Range in Bulk How to Create and Use Configuration files in a Python Project Check if a Value Already Exists in a List of Dictionary Objects in Python How to Split Large Files by size in Python? Fixing - Running Scripts is Disabled on this System Error on Windows Generating QR Codes in Python Reading QR Codes in Python

How to Create and Use Configuration files in a Python Project

  • Last updated Apr 26, 2024

A configuration file is a file that contains data about a program or specific user settings that is needed to run the application. Every program needs some kind of configuration. These configuration data could be written straight into the source code for extremely simple jobs. However, this is a bad idea because you may need to upload your project code to Github. As a result, it's better to build and use individual configuration files rather than pushing them to Github or other such repositories.

There are many types of configuration files. In this tutorial, we will show you how to create and use configuration files in Python.

Creating .ini config files

The .ini file is a configuration file with .ini extension. Python provides a built-in module called configparser to read .ini files.

Create a config.ini file inside your project directory and add configuration details to it in the following format:

[DATABASE]
host = localhost
port = 3306
username = root
password = Test123$
database_name = "test"
pool_size = 10

[S3]
bucket = test
key = HHGFD34S4GDKL452RA
secret = YKH1jsPQks35/hs3HS34jslkYo4wSYu
region = us-west-1

To retrieve configuration details from the config.ini file in your Python code, do the following:

from configparser import ConfigParser
import os.path

dir_path = os.path.dirname(os.path.realpath(__file__))
config_filepath = dir_path+"/config.ini"
# check if the config file exists
exists = os.path.exists(config_filepath)
config = None
if exists:
    print("--------config.ini file found at ", config_filepath)
    config = ConfigParser()
    config.read(config_filepath)
else:
    print("---------config.ini file not found at ", config_filepath)

# Retrieve config details
database_config = config["DATABASE"]
s3_config = config["S3"]
# Never print config data in console when working on real projects
print(database_config["host"])
print(database_config["port"])
print(database_config["username"])
print(database_config["password"])
print(database_config["database_name"])
print(database_config["pool_size"])

print(s3_config["bucket"])
print(s3_config["key"])
print(s3_config["secret"])
print(s3_config["region"])

The output of the above code is as follows:

--------config.ini file found at E:\python-workspace\example/config.ini
localhost
3306
root
Test123$
test
10
test
HHGFD34S4GDKL452RA
YKH1jsPQks35/hs3HS34jslkYo4wSYu
us-west-1