Last updated: Apr 9, 2024
Reading timeยท3 min
The Python "ModuleNotFoundError: No module named 'encodings'" occurs for multiple reasons:
Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings'
The first thing you should try is to recreate your virtual environment if you have one.
# ๐๏ธ Optionally update your requirements.txt file pip freeze > requirements.txt # ๐๏ธ Deactivate virtual environment deactivate # ๐๏ธ Remove the old virtual environment folder: macOS and Linux rm -rf venv # ๐๏ธ Remove the old virtual environment folder: Windows rd /s /q "venv" # ๐๏ธ specify correct Python version when creating virtual environment python -m venv venv # ๐๏ธ Activate on Unix or MacOS source venv/bin/activate # ๐๏ธ Activate on Windows (cmd.exe) venv\Scripts\activate.bat # ๐๏ธ Activate on Windows (PowerShell) venv\Scripts\Activate.ps1 # ๐๏ธ Install the modules in your requirements.txt file (optional) pip install -r requirements.txt
If the python -m venv venv
command doesn't work, try the following 2 commands:
python3 -m venv venv
py -m venv venv
Make sure to use the correct activation command depending on your operating system and your shell.
Try running your script with the new virtual environment active.
Here is an example of how to correctly set up Python on Windows and add Python to the PATH environment variable in a straightforward way.
Download the installer from the official python.org website.
If you have Python already installed, start the installer and click on "Modify".
You can leave the optional features ticked.
On the "Advanced Options" screen, make sure to tick the "Add Python to environment variables" option.
Once the "Add Python to environment variables" checkbox is checked, click "Install".
If that didn't work, your Python installation might be corrupted.
Start the installer again and click on "Uninstall".
The checkbox won't be checked by default.
Once the "Add python.exe to PATH" checkbox is checked, click on "Install Now".
After the installation, Python will be installed and configured properly.
If you are on Linux or macOS, check if you have the PYTOHNHOME
environment
variable set to a wrong value.
echo $PYTOHNHOME echo $PYTHONPATH
If the environment variables are incorrectly set, you can try to remove them and restart your machine.
unset PYTOHNHOME
If that doesn't help, try reinstalling Python from the official python.org website.
To solve the "ModuleNotFoundError: No module named 'encodings'" error, make sure: