ImportError: No module named PIL

Here is a code snippet that demonstrates how to catch the "ImportError: No module named PIL" error:

try:
    from PIL import Image
except ImportError:
    import Image

This code attempts to import the Image module from the PIL package. If the PIL package is not installed, the import will fail and raise an ImportError, which is caught by the except block. In this case, the code will then try to import the Image module from the standard library.

Watch a course Python - The Practical Guide

It is important to note that PIL is not maintained since 2011, the python Imaging Library (PIL) is no longer maintained. A more recent fork named Pillow is available, you can install it via pip package installer by running pip install Pillow in your command prompt or terminal.

import PIL

or

from PIL import Image

This will work if you have Pillow library installed on your machine.