close

[Solved] SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in python3

Hello Guys, How are you all? Hope You all Are Fine. Today when I try to read file I get following error in my stack track SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in python3 in Python. So Here I am Explain to you all the possible solutions here.

Without Wasting your time, Lets start This Article to Solve This Error.

How This SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in python3 Occurs ?

I am using Python 3.7 in my windows 10. I am just trying to open file through codecs module with utf-8. But It give me following error.

>>> fileData = codecs.open("C:\Users\ssc\Desktop\coreData.txt", "r", encoding="utf-8")

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#39>, line 1)

How To Solve SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in python3?

Question: How To Solve SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in python3?
Answer: To Solve SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in python3 you just need to duplicate all backslashes OR prefix the string with r (to produce a raw string). Just duplicate all backslashes. As like below OR Or just prefix the string with r as same as below.

Solution 1

Here I can see the problem is your File Path. To solve this error you just need to duplicate all backslashes OR prefix the string with r (to produce a raw string).

Just duplicate all backslashes. As like below.

"C:\\Users\\ssc\\Desktop\\coreData.txt"

Or just prefix the string with r as same as below.

r"C:\Users\ssc\Desktop\coreData.txt"

Solution 2

You just need to Prefixing with 'r' works very well, but it needs to be in the correct syntax. Just like below.

fileData = open(r'''C:\Users\ssc\Desktop\coreData.txt''')

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment