To fix the ModuleNotFoundError: no module named ‘dotenv’ error, install the dotenv module by python3 -m pip install python-dotenv command.
python3 -m pip install python-dotenv
The above command will install the dotenv module.
If you use a virtual environment, ensure you have activated it before running the pip command. Use pip3 instead of pip if you have multiple versions of Python installed on your system.
Using the pip show python-dotenv command will either state that the package is not installed or show a bunch of information about the package, including the location where the package is installed.
Create a .env file in your project’s root folder. Add the following code to it.
DOMAIN=appdividend.com
ADMIN_EMAIL=admin@appdividend.com
After installing the python-dotenv package, import it into your script file.
import os
from dotenv import load_dotenv
load_dotenv()
print(os.environ.get('DOMAIN'))
print(os.environ.get('ADMIN_EMAIL'))
Output
appdividend.com
admin@appdividend.com
And we have successfully installed the dotenv module in our system.
In another case, if you’re using a different package manager, such as conda, install the dotenv module using that package manager instead.
The python-dotenv module allows you to load environment variables from a .env file in your Python project. It helps store sensitive information you don’t want to hardcode into your code.
Why does the ModuleNotFoundError: no module named ‘dotenv’ error occur?
Python raises the ModuleNotFoundError: no module named ‘dotenv’ error when it cannot find the dotenv module in your project because the dotenv module is not installed in your environment. For example, if developers forget to install the python-dotenv module before using it, this error will be thrown.
Other multiple reasons for errors to occur
- If you are using a virtual environment, the package might not be installed in that environment, and it is installed globally.
- You are using an IDE that uses an incorrect version of Python.
- Declaring a variable named dotenv, which would shadow the imported variable.
- Ensure you haven’t named a module in your project as dotenv.py because it would shadow the main dotenv module.
Conclusion
The “ModuleNotFoundError: No module named ‘dotenv'” error occurs when we forget to install the python-dotenv module before fixing the error; install the module by running the pip install python-dotenv command.