[Solved] ModuleNotFoundError: No module named ‘PIL’

When working with the Python library Pillow, getting this error means that you forgot to install it first. You can fix this by installing it with pip: pip install Pillow.

Problem: the Pillow package isn’t installed yet

If you’re trying to use the Python Imaging Library (PIL) – which has since been superseded by a new project called “Pillow” which you can still import the same way – you might come across this error if you haven’t installed it yet.

Below is some code that uses the PIL import (remember, this is still the Pillow library, they allow importing it like this for backward compatibility):

from PIL import Image

dog_image = Image.open("dog.jpg")
print(dog_image.format, dog_image.size, dog_image.mode)
Python

If you run the above code without installing the Pillow package first, you’ll get the following error message:

Traceback (most recent call last):
  File "/home/user/main.py", line 1, in <module>
    from PIL import Image
ModuleNotFoundError: No module named 'PIL'

As the message says, the module wasn’t found, meaning it’s probably not installed. So, let’s fix that.

Fix: Install the Pillow package with pip

You can fix this error by using the Python package manager pip to install the Pillow package.

The command to do so as well as the output can be seen below:

(venv) john@codehammer ~/c/a/whatever [0|1]> pip install Pillow
Collecting Pillow
  Downloading Pillow-10.0.0-cp310-cp310-manylinux_2_28_x86_64.whl (3.4 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.4/3.4 MB 19.4 MB/s eta 0:00:00
Installing collected packages: Pillow
Successfully installed Pillow-10.0.0
ShellScript

Now that we’ve successfully installed Pillow, let’s run our Python script again:

JPEG (3840, 2160) RGB

Looks like it’s working!

Conclusion

If you get a “module not found” error when running a Python script, it almost always means you need to install a 3rd party Python module in order to run it. In this case, we were missing the Pillow package, which is used to work with images in Python. Simply run pip install Pillow to correct this error.