0
0
PythonHow-ToBeginner · 3 min read

How to Use dotenv in Python: Load Environment Variables Easily

To use dotenv in Python, install the python-dotenv package, create a .env file with your variables, and load them in your script using load_dotenv(). Then access variables with os.getenv() or os.environ.
📐

Syntax

Here is the basic syntax to use dotenv in Python:

  • from dotenv import load_dotenv: Imports the function to load environment variables.
  • load_dotenv(): Reads the .env file and loads variables into the environment.
  • os.getenv('VAR_NAME'): Retrieves the value of the environment variable named VAR_NAME.
python
from dotenv import load_dotenv
import os

load_dotenv()  # Load variables from .env file
my_var = os.getenv('MY_VAR')  # Get the variable value
print(my_var)
💻

Example

This example shows how to load a variable from a .env file and print it.

Create a file named .env with the content:

GREETING=Hello, world!

Then run the Python script below.

python
from dotenv import load_dotenv
import os

load_dotenv()  # Load variables from .env file

greeting = os.getenv('GREETING')
print(greeting)
Output
Hello, world!
⚠️

Common Pitfalls

Common mistakes when using dotenv include:

  • Not installing the python-dotenv package.
  • Forgetting to call load_dotenv() before accessing variables.
  • Not placing the .env file in the correct directory (usually the project root).
  • Trying to access variables with os.environ['VAR_NAME'] without checking if they exist, which can cause errors.

Always use os.getenv() to safely get variables or provide a default value.

python
from dotenv import load_dotenv
import os

load_dotenv()

# Wrong: may raise KeyError if VAR_NAME not set
# print(os.environ['VAR_NAME'])

# Right: returns None if VAR_NAME not set
print(os.getenv('VAR_NAME'))
Output
None
📊

Quick Reference

StepDescription
Install packageRun pip install python-dotenv
Create .env fileAdd key=value pairs, e.g., API_KEY=12345
Load variablesCall load_dotenv() in your script
Access variablesUse os.getenv('KEY') to get values

Key Takeaways

Install python-dotenv and create a .env file to store environment variables safely.
Call load_dotenv() before accessing variables to load them into your program.
Use os.getenv() to get environment variables safely without errors.
Keep your .env file outside version control to protect sensitive data.