Install python-dotenv and use load_dotenv() to load .env files into the process environment. Understand env var precedence, handle missing .env files safely, and learn why .env files must never be committed to source control ā with a .gitignore pattern and a .env.example template to enforce that boundary.
Create the lesson-303 directory, activate the virtual environment, install python-dotenv, and write a `.env` file that holds an API key, a base URL, and a debug flag. Then verify that load_dotenv() makes those values available to os.getenv().
mkdir -p ~/devops-python/lesson-303cd ~/devops-python/lesson-303source ~/devops-python/lesson-101/devops-env/bin/activatepip install "python-dotenv>=1,<2"pip show python-dotenv | grep -E 'Name|Version'# Deployment secrets ā DO NOT COMMIT THIS FILE
API_KEY=secret-key-abc123
API_BASE_URL=https://api.example.internal
DEBUG=true
MAX_RETRIES=3import os
from dotenv import load_dotenv
from pathlib import Path
# Load the nearest .env file using python-dotenv's default search.
# For a fixed location, pass dotenv_path=Path(__file__).resolve().parent / '.env'.
loaded = load_dotenv()
print(f'load_dotenv() returned: {loaded}')
print()
print(f'API_KEY: {os.getenv("API_KEY")}')
print(f'API_BASE_URL: {os.getenv("API_BASE_URL")}')
print(f'DEBUG: {os.getenv("DEBUG")}')
print(f'MAX_RETRIES: {os.getenv("MAX_RETRIES")}')python3 verify_load.pypython-dotenv is not part of the Python standard library, so it must be installed with pip.
The version pin python-dotenv>=1,<2 locks to the v1.x stable series.
The .env file is a plain text file where each line is a KEY=value pair.
Lines starting with # are comments and are ignored. load_dotenv() uses find_dotenv() when you do not pass dotenv_path=; in a normal script that means it searches for the nearest .env file by walking upward from the calling script's directory.
It parses each KEY=value line and calls os.environ.__setitem__() for any key not already present in the process environment.
After load_dotenv() returns, the values are available through the standard os.getenv() and os.environ interfaces ā no dotenv-specific API is needed to read them.
pip show prints Name: python-dotenv and Version: 1.x. verify_load.py prints load_dotenv() returned: True, then API_KEY: secret-key-abc123, API_BASE_URL: https://api.example.internal, DEBUG: true, and MAX_RETRIES: 3.