You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python打开PNG与JPG文件?PIL模块报错求解决方案

Hey there! Let's break down your two Python image handling questions clearly, step by step.

1. How to Open PNG and JPG Files in Python

The most common and straightforward way to work with these image formats is using the Pillow library (a maintained fork of the old PIL library). Here's how to do it:

Using Pillow

  • First, make sure you have Pillow installed (note: it's pillow not PIL when installing via pip):
    pip install pillow
    
  • Then use the Image.open() method to load either PNG or JPG files—this method works seamlessly for both formats:
    from PIL import Image
    
    # Open a PNG file
    png_image = Image.open("D:/foto's/fbshare.png")
    # Open a JPG file
    jpg_image = Image.open("path/to/your/image.jpg")
    
    # To view the image, use the show() method
    png_image.show()
    jpg_image.show()
    

Alternative: Using OpenCV

If you're working on computer vision tasks, OpenCV is another great option:

  • Install OpenCV:
    pip install opencv-python
    
  • Load and display images:
    import cv2
    
    png_img = cv2.imread("D:/foto's/fbshare.png")
    jpg_img = cv2.imread("path/to/your/image.jpg")
    
    # Display images (press any key to close windows)
    cv2.imshow("PNG Image", png_img)
    cv2.imshow("JPG Image", jpg_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
2. Fixing the AttributeError: partially initialized module 'PIL.Image' has no attribute 'open' Error

This error almost always happens because of a naming conflict or corrupted library installation. Here's how to fix it:

  • Check your script filename: The biggest culprit is naming your own Python script PIL.py, Image.py, or any other name that matches a module in the Pillow library. When you run from PIL import Image, Python will try to import your local script instead of the actual Pillow library, causing a circular import. Rename your script to something unique (like image_viewer.py).
  • Delete cached files: If there's a __pycache__ folder or .pyc files in your script directory, delete them. These cached files might still reference the old, conflicting module.
  • Reinstall Pillow (if needed): If the above steps don't work, a corrupted installation might be the issue. Uninstall and reinstall Pillow to get a fresh copy:
    pip uninstall pillow -y
    pip install pillow
    
  • Verify the import path: To double-check you're importing the correct library, add this to the top of your script:
    import PIL
    print(PIL.__file__)
    
    The output should point to the Pillow library in your Python site-packages folder (e.g., C:\Python311\Lib\site-packages\PIL\__init__.py), not your local script.

内容的提问来源于stack exchange,提问作者tenn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:14:38