-1

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

I wrote this code :

from playsound import playsound
playsound('C:\Users\City Computer\Music\New folder\\play.mp3')
jps
  • 20,041
  • 15
  • 75
  • 79
  • there is a problem with your path passed to the function. as a simple backslash is an escape character in python – jodá Jul 23 '21 at 08:12
  • i also have tried double slashes in but it still give me this error – Atif Hameed Jul 23 '21 at 08:19
  • Does this answer your question? ["Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3](https://stackoverflow.com/questions/1347791/unicode-error-unicodeescape-codec-cant-decode-bytes-cannot-open-text-file) – Valentin M. Jul 23 '21 at 13:56

1 Answers1

1

Here, \U in the path 'C:\Users... starts an eight-character Unicode escape, such as \U00014321. In your code, the escape is followed by the character 's', which is invalid. (As explained here)

Solutions:

There are three ways to solve this issue

1. Duplicate all backslashes (basically escape the escape character)

'C:\\Users\\City Computer\\Music\\New folder\\play.mp3'

2. Prefix the string with r (to produce a raw string)

r'C:\Users\City Computer\Music\New folder\play.mp3'

3. Use forward slashes(/) to avoid confusion

'C:/Users/City Computer/Music/New folder/play.mp3'
K450
  • 691
  • 5
  • 17
  • 1
    Your answer is correct. But you have mentioned a link to another post on SO. It means that the question is duplicate. You should flag it as a duplicate –  Jul 23 '21 at 08:50
  • The reason I didn't flag it as duplicate is that the link I provided didn't included the 3rd solution. If I should have still flagged it as duplicated, then I apologize for my ignorance. – K450 Jul 23 '21 at 09:05