| icon | lucide/rocket |
|---|
This tutorial walks you through installing python-dotenv and using it to load
environment variables from a .env file.
=== "pip"
```shell
pip install python-dotenv
```
=== "uv"
```shell
uv add python-dotenv
```
Add a .env file to the root of your project:
.
├── .env
└── app.py
Write your configuration as key-value pairs:
# .env
DOMAIN=example.org
ADMIN_EMAIL=admin@${DOMAIN}
ROOT_URL=${DOMAIN}/appIf you use variables in values, ensure they are surrounded with { and },
like ${DOMAIN}, as bare variables such as $DOMAIN are not expanded. See
Variable expansion for the full
syntax.
!!! tip
Add `.env` to your `.gitignore`, especially if it contains secrets.
In your Python application:
from dotenv import load_dotenv
import os
load_dotenv()
domain = os.getenv("DOMAIN")
print(domain) # example.orgload_dotenv() looks for a .env file starting in the same directory as the
calling script, walking up the directory tree until it finds one. Each key-value
pair is added to os.environ.
By default, load_dotenv():
- Searches for a
.envfile automatically usingfind_dotenv(). - Reads each key-value pair and adds it to
os.environ. - Does not override existing environment variables. Pass
override=Trueto change this.
# Override existing environment variables
load_dotenv(override=True)- Configuration Patterns: load config as a dict, layer multiple
.envfiles. - Command-line Interface: manage
.envfiles and run commands from the terminal. - File Format: full specification of
.envfile syntax. - Python API Reference: all functions and their parameters.