如何用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
pillownotPILwhen 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 runfrom 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 (likeimage_viewer.py). - Delete cached files: If there's a
__pycache__folder or.pycfiles 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:
The output should point to the Pillow library in your Python site-packages folder (e.g.,import PIL print(PIL.__file__)C:\Python311\Lib\site-packages\PIL\__init__.py), not your local script.
内容的提问来源于stack exchange,提问作者tenn
相关产品推荐
相关产品推荐

