Deepthy
Deepthy

Reputation: 13

Syntax error:unicode error on trying to open image using PIL in Python

I am new to Python. I was trying to open an image using Python Pillow.But

    >>> from PIL import Image
    >>> im=Image.open("C:\Users\User1\Desktop\map3.jpg")
      File "<stdin>", line 1
    SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in  position 2-3: truncated \UXXXXXXXX escape

I tried using the image name alone and it still didn’t work

    >>> from PIL import Image
    >>> im=Image.open("map3.jpg")
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Users\Deepthy\AppData\Local\Programs\Python\Python35-32\lib\site-    packages\PIL\Image.py", line 2258, in open
        fp = builtins.open(filename, "rb")
    FileNotFoundError: [Errno 2] No such file or directory: 'map3.jpg'

Upvotes: 1

Views: 3100

Answers (1)

dsh
dsh

Reputation: 12214

The problem originates with Windows' legacy. Try this instead:

im=Image.open("C:/Users/User1/Desktop/map3.jpg")

In Python source code, just as in most other languages including C, C++, Java, Javascript, C#, Ruby, Perl and PHP, the backslash is an escape character. It is used to indicate that the following character(s) have special meaning. In a string literal in Python, \u (or \U) begins a Unicode escape sequence. However, \Users is not a valid Unicode escape. Something like \u20ac would be valid (and is the euro currency symbol).

I say that the problem originates with Windows' legacy because Windows (and MS-DOS, before it) chose to use the backslash as the separator character in paths. This is unfortunate since the backslash already held special meaning in program source code so it needs to be escaped, for example print("How many do you see \\?"). Alternatively, the Windows API functions all accept a slash instead of a backslash even though the GUI programs (Explorer, cmd.exe) do not.

Your second problem (the FileNotFoundError) is correct: you specified a relative path but the file does not exist in the current working directory as you specified.

Upvotes: 2

Related Questions