Explain Codes LogoExplain Codes Logo

Importerror: No module named PIL

python
importerror
pillow
image-manipulation
Anton ShumikhinbyAnton Shumikhin·Dec 1, 2024
TLDR

Encountered ImportError? Solve it by moving to Pillow, the updated replacement for PIL, by running:

pip install Pillow

Now, to handle images, include the following import statement:

from PIL import Image

For Python 3, replace pip with pip3.

Understanding the ImportError: In a nutshell

The dreadful ImportError: No module named PIL occurs when your Python environment lacks a necessary library for image manipulation. Although Python Imaging Library (PIL) was traditionally used for this purpose, its development has ceased. As a result, the community pivoted to Pillow, which is more user-friendly and indeed, a fork of PIL.

Why Pillow over PIL?

Transitioning from PIL to Pillow not only fixes the ImportError but helps you leverage enhanced features, regular updates, and ease of use offered by Pillow. If the ImportError persists after installation, consider checking your Python environment for multiple Python versions or if you're running a virtual environment.

Handling the switch: From PIL to Pillow

When migrating from PIL to Pillow, it's critical to uninstall PIL properly first using pip uninstall PIL. Afterwards, install Pillow via pip install Pillow. Remember, in certain cases (on Linux systems or dealing with permissions), using superuser rights with sudo is necessary, for example, sudo pip install Pillow.

Advanced Troubleshooting Techniques

If you've followed the steps mentioned and the problem continues, let's delve into some deeper diagnostic steps and advanced resolutions.

Spot the discrepancy: Check your path

Ensure that your system's PATH environment variable includes Python’s install path. If not, your Python environment doesn't know where to find the Pillow module, leading to the ImportError.

Fresh beginning: Clean up your environment

Sometimes, all your environment needs is a fresh start. A clean install in a new virtual environment often acts as a silver bullet:

python -m venv new-env
source new-env/bin/activate (On Windows use `new-env\Scripts\activate`)
pip install Pillow

Battle of packages: Look for conflicting packages

Inspect your installed packages using pip freeze. On rare occasions, another package could conflict with Pillow's installation.

Binary dependencies: Is everything installed?

Pillow depends on several binary libraries like libjpeg and zlib. Ensure these are installed on your system. Most systems include these with Pillow, but exceptions do exist.