Python Dotenv Module
The python-dotenv library reads key-value pairs from a .env file and can set them as environment variables. It helps in the development of applications following the 12-factor principles.
Installation
pip install python-dotenv
Basic Usage
Create a .env file in your project root:
API_KEY=your_api_key_here
DATABASE_URL=postgres://user:pass@localhost:5432/db
DEBUG=True
Then load it in your Python script:
import os
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Access variables
api_key = os.getenv("API_KEY")
database_url = os.getenv("DATABASE_URL")
print(f"API Key: {api_key}")
Overriding System Variables
By default, load_dotenv does not override existing environment variables. To override them, use override=True.
load_dotenv(override=True)
Loading Specific Files
You can specify a path to a specific env file.
from pathlib import Path
from dotenv import load_dotenv
env_path = Path('.') / '.env.dev'
load_dotenv(dotenv_path=env_path)