pythonimagepython-imaging-library

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\User\\Downloads.png' in Python


Everything was going smoothly until I tried to use PIL, I have been stuck on this for a few days, so if you can help, it will be very good.

import PIL
from PIL import Image
fp = Image.open(r"C:\Users\User\Downloads.png")
im.show()

I have also tried different ways like:

import PIL
from PIL import Image
file_name="C:\Users\User\Downloads.png"
fp = Image.open(file_name,"r")
im.show()

Which has shown:

none
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

I have also changed it to:

file_name="C:\\Users\\User\\Downloads.png"

But it shows another error:

But it mostly shows:

none
Traceback (most recent call last):
  File "C:\Users\User\pythonProject\.venv\image 0.1.py", line 4, in <module>
    fp = Image.open(file_name,"r")
         ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\pythonProject\.venv\Lib\site-packages\PIL\Image.py", line 3431, in open
    fp = builtins.open(filename, "rb")
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\User\\Downloads.png'

I am on Windows and use PyCharm; if you can help, it will be amazing.


Solution

  • I was able to download PIL (see this link: [Pillow Documentation])1 and run the code successfully using a png file in my downloads folder

    Here is the code:

    import PIL
    from PIL import Image
    fp = Image.open('/Users/xxx/Downloads/Screenshot 2024-07-13 at 5.48.46 PM.png') # please replace 'xxx' with your path name
    fp.show()  # I changed 'im' to 'fp' since 'im' is not defined
    

    Here is the image I gotmy local png file

    Feel free to follow up if it's still not working.

    Regarding system difference, I am using a Mac but have PC too. I can check that out for you too. A potentially useful trick to share regarding using PC: you can go to the folder with your png file of interest, pressing 'shift' button while right click. That way, you will see an option to copy the path of the file. Then you just need to paste it to your code (saving the typing work and also avoiding chance of errors). Pay attention to r string and add it if needed. Hope this helps.