Fixing the “ModuleNotFoundError: No module named ‘dotenv'” Error in Python

When developing Python applications, you may encounter the error “ModuleNotFoundError: No module named ‘dotenv'” which occurs when trying to import and use the python-dotenv module.

The dotenv module allows you to load environment variables from a .env file, helping manage configuration separately from code. Fixing this error is necessary to use the powerful functionality dotenv provides.

In this comprehensive guide, we’ll cover:

  • What causes the “No module named dotenv” error
  • Steps to fix it and import dotenv properly
  • Using pip and virtual environments to install dotenv
  • Importing dotenv and loading .env files
  • Best practices for managing app configuration with dotenv

Follow along to understand what causes this error, and how to properly install, import, and use python-dotenv in your Python projects.

What Causes the “No module named dotenv” Error?

Python throws the “No module named dotenv” error when you try to import dotenv but the module is not actually installed.

This can happen for a few reasons:

  • dotenv is not installed – Most commonly, dotenv is not yet installed in the current environment. The import fails because Python cannot find the module.
  • Using the wrong name – Attempting to import the wrong name like ‘env’ instead of ‘dotenv’ will also fail.
  • Multiple Python versions – If you install dotenv in one Python version but run code in another, the import may fail.
  • Virtual environments – If dotenv is installed globally but not in the current virtual environment, the import will fail only in that environment.

The root cause is that Python cannot locate the dotenv module, so it throws the ModuleNotFoundError when trying to import it.

Steps to Fix the “No module named dotenv” Error

To successfully fix the error and use dotenv in your project, follow these steps:

1. Install the python-dotenv Package

First, you need to install the dotenv module from PyPI.

Use pip to install to your global Python environment:

pip install python-dotenv

Or for a specific project, install to a virtual environment:

# Create virtual env 
python -m venv env

# Activate virtual env
source env/bin/activate

# Install to virtual env
pip install python-dotenv

This will download the latest version and make dotenv available for import.

2. Import dotenv Correctly

With dotenv installed, you can now import it in your Python code:

import dotenv

Make sure to use the correct name dotenv and not a typo.

3. Load Variables from the .env File

After importing dotenv, load environment variables from your .env file:

import dotenv

# Load environment variables 

This will read key-value pairs from the .env file and set them as environment variables in your code.

4. Access Environment Variables

Finally, you can now access any environment variables loaded from .env:

import os
import dotenv

# Load .env

# Access environment variables
db_user = os.environ['DB_USER']
db_pass = os.environ['DB_PASS']

# prints database username from .env

This allows separating configurations from code while still making them available at runtime.

Following these steps will resolve the import error while also enabling use of dotenv for environment variable management.

Using pip and Virtual Environments

When installing python-dotenv, it is highly recommended to use pip and virtual environments to manage dependencies and environments.

Here are some best practices:

  • Always install dotenv using pip install python-dotenv. Avoid manual installation.
  • Use virtual environments via python -m venv for isolating project configurations.
  • Install dotenv to the virtual environment when working on a specific project.
  • Upgrade dotenv using pip install --upgrade python-dotenv to fix issues.
  • List installed packages with pip list to confirm dotenv is present.
  • Delete and recreate virtual environments if configurations are lost.

Following these pip and virtual environment best practices will help avoid tricky environment and configuration issues that can prevent importing dotenv.

Importing dotenv and Loading .env Files

When using dotenv in Python code, follow these best practices:

  • Import dotenv near the top of files before it is used.
  • Load environment variables by calling dotenv.load_dotenv() before accessing them.
  • Load .env from the project root, or specify the full path like dotenv.load_dotenv('/path/to/.env').
  • Handle OSError errors when loading .env in case the file is missing.
  • Call dotenv.load_dotenv() again after making changes to .env to reload.
  • Import and load dotenv only in scripts that need access to environment variables.

Simple examples:

# At top of file
import dotenv 
import os

# Load .env file
import dotenv

  # Load environment variables

except OSError:
  # Handle error loading .env
  print("Error loading .env file")

This will properly import dotenv, load variables from .env, and handle potential errors when loading.

Best Practices for Managing App Config with python-dotenv

Here are some top practices for managing application configuration with dotenv:

  • Store default configs in .env.example – Version control this file with examples and defaults for other developers.
  • Add .env to .gitignore – Sensitive credentials should only exist locally in .env, which should not be committed.
  • Document required variables – Use .env.example to document what keys need to be in .env.
  • Load .env as early as possible – Load environment variables at the top of app entry points.
  • Use sane defaults – Code that accesses environ variables should handle unset values graciously.
  • Access variables using os.environ[] – This ensures variables are read correctly across contexts.
  • Validate variable values – Type check and validate critical configuration values after loading.
  • Load based on environment – Load different .env files like .env.production based on context.
  • Security: avoid committing secrets – Never commit .env or other files with secrets to version control.

Following these practices for your Python application configurations will prevent issues and help make configuration management seamless across development, testing, and production environments.


The “ModuleNotFoundError: No module named ‘dotenv'” Python error occurs when python-dotenv is not installed or imported correctly. To fix it, install dotenv using pip, import it, call the load_dotenv() method, and access environment variables through os.environ.

Dotenv provides an efficient way to manage configuration separate from code. Using pip and virtual environments isolates app dependencies, while following best practices for importing and loading dotenv prevents issues accessing environment variables.

With dotenv correctly installed and imported, you can build robust Python applications with configurable settings across multiple environments. Diagnosing and fixing “No module named dotenv” errors ensures critical app configurations load reliably.

Leave a Comment