Use python-dotenv to Load Environment Variables from a .env file in Python
How to load .env files in Python using python-dotenv
Published by Carlo van Wyk on June 16, 2025 in Python

Python-dotenv lets you load environment variables from a .env file into your Python application. Here's how to implement it:
First, install python-dotenv using pip:
pip install python-dotenv
Create a .env file in your project root directory and add your environment variables:
API_KEY=your_secret_key_here
DATABASE_URL=postgresql://user:pass@localhost/db
DEBUG=True
Load the variables in your Python code:
from dotenv import load_dotenv
import os
load_dotenv() # Load environment variables from .env
api_key = os.getenv('API_KEY')
database_url = os.getenv('DATABASE_URL')
debug = os.getenv('DEBUG')
For automatic loading, you can also use:
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
Python-dotenv also supports setting default values and type casting:
debug = os.getenv('DEBUG', default=False)
port = int(os.getenv('PORT', 3000))