[Solved]: Python SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape

Python SyntaxError occurred when you are trying to access a path with normal String. As you know ‘/’ is escape character in Python that’s having different meaning by adding with different characters for example ‘\n’ is use for one line , ‘\t’ use for tab.

This error is considered as Python SyntaxError because unicode forward slash (\) is not allow in path.

In further section of topic you will learn how to handle this problem in Python while writing path of file to access it.

See Also:

Example of Python SyntaxError of Unicode Error

Lets take below example to read CSV file in Windows operating system.

import csv
with open('C:\Users\saurabh.gupta\Desktop\Python Example\input.csv','r') as csvfile:
    for record in reader:

If you notice the above code is having path for windows file system to access input.csv. In windows path mentioned by using forward slash (\) while in Python programming forward slash(\) is use for handling unicode characters. That’s why when you execute the above program will throw below exception.


File "C:/Users/saurabh.gupta14/Desktop/Python Example/ReadingCSV.py", line 2
    with open('C:\Users\saurabh.gupta\Desktop\Python Example\input.csv','r') as csvfile:


The above error is occurred because of handling forward slash(\) as normal string. To handle such problem in Python , there are couple of solutions:

1: Just put r in path before your normal string it converts normal string to raw string:

with open(r'C:\Users\saurabh.gupta\Desktop\Python Example\input.csv','r') 

2: Use back slash (/) instated of forward slash(\)

with open('C:/Users/saurabh.gupta/Desktop/Python Example/input.csv','r') 

3: Use double forward slash (\\) instead of forward slash(\) because in Python the unicode double forward value convert in string as forward slash(\)’

with open('C:\\Users\\saurabh.gupta\\Desktop\\Python Example\\input.csv','r') 

If this solution help you , Please like and write in comment section or any other way you know to handle this issue write in comment so that help others.

Related Posts

Your Feedback Motivate Us

If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

Happy Learning !!!