Published on Thursday, December 26, 2024
How to Load a .env File in Python Using python-dotenv
Posted by

Video Tutorial
Step 1: Install python-dotenv
Install the python-dotenv package with pip:
pip install python-dotenv
This tool lets you manage environment variables efficiently.
Step 2: Create a .env File
In your project’s root directory, create a .env file to store key-value pairs. For example:
DATABASE_URL=postgres://user:password@localhost:5432/mydatabase
SECRET_KEY=mysecretkey123
DEBUG=True
This file securely holds variables like database credentials and API keys.
Step 3: Load Environment Variables in Python
1. Import Required Modules
In your Python script, import the necessary modules:
from dotenv import load_dotenv
import os
2. Load the .env File
Use load_dotenv to load variables into your environment:
load_dotenv()
Note:
By default, load_dotenv() searches for a .env file in the current working directory. If you have custom .env files (e.g., .env.local, .env.production), you can specify the file path:
load_dotenv(".env.local")
3. Access the Variables
Retrieve variables using os.getenv():
database_url = os.getenv("DATABASE_URL")
secret_key = os.getenv("SECRET_KEY")
debug_mode = os.getenv("DEBUG")
print(f"Database URL: {database_url}")
print(f"Secret Key: {secret_key}")
print(f"Debug Mode: {debug_mode}")
This code fetches values from the .env file and prints them, verifying they’ve been loaded correctly.
Step 4 (Optional): Ignore .env File in .gitignore
For security, add your .env file to .gitignore to prevent it from being committed to version control:
# .gitignore
.env
This ensures sensitive information remains private and secure.
Conclusion
With python-dotenv, managing environment variables becomes straightforward and secure. By keeping sensitive data out of your source code, you enhance both security and organization. Whether you’re building a simple script or a large application, this approach ensures clean and efficient configuration management.