PromptHub
Python Beginner 13 views

Python PIL/Pillow Image Not Found

The PIL/Pillow library cannot locate an image file at the specified path.

Explanation

When using PIL/Pillow (Python Imaging Library), trying to open an image that doesn't exist raises a FileNotFoundError (in newer versions) or PIL.UnidentifiedImageError. This is technically an OSError/FileNotFoundError but is commonly encountered in image processing workflows. The error can also occur when the file exists but is corrupted, has the wrong extension, or is in an unsupported format. Note that PIL is the old library; Pillow is the maintained fork that provides backward compatibility.

Common Causes

  • Image file doesn't exist at path
  • File path typo
  • File was not fully uploaded
  • Image is corrupted
  • Wrong file extension

Solution

Verify the image file path is correct and the file exists. Check the file extension matches the actual format. Ensure Pillow is installed: pip install Pillow. Use os.path.exists() to check before opening. Verify the file isn't corrupted by opening it in an image viewer. Check file permissions. For web uploads, ensure the file was fully uploaded before processing. Use pathlib.Path for modern path handling.

Code Example

from PIL import Image

# FileNotFoundError if image doesn't exist
try:
    img = Image.open('uploads/photo.jpg')
except FileNotFoundError:
    print('Image not found')

# Fix: check existence first
from pathlib import Path
image_path = Path('uploads/photo.jpg')
if image_path.exists():
    img = Image.open(image_path)
else:
    img = Image.new('RGB', (100, 100), 'gray')

# Handle different error types
try:
    img = Image.open('photo.jpg')
    img.verify()  # verify it's a valid image
except FileNotFoundError:
    print('File not found')
except (IOError, SyntaxError) as e:
    print('Bad image:', e)

# For web uploads
if request.files['image']:
    file = request.files['image']
    temp_path = os.path.join(UPLOAD_DIR, file.filename)
    file.save(temp_path)
    img = Image.open(temp_path)

Error Information

Language

python

Difficulty

Beginner

Views

13

Related Errors