I was developing an application in python using Pycharm IDE installed in my windows laptop.

I got the following error while trying to read a file using a python program. This happened in my windows laptop. The error message is given below.
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
The piece of code that throwed this exception is given below.
fr = open("C:\Users\Amal\PycharmProjects\data\out.csv", "r")
data = fr.read()
The first line of the above code was throwing this error. On further troubleshooting, I found the issue and solved it. The issue was because of the way I passed the file path string. The following solutions will work well to fix the issue.
Solution: 1
Put an r before the path. This will convert the normal string to raw string. The sample code snippet after making the change is given below.
fr = open(r"C:\Users\Amal\PycharmProjects\data\out.csv", "r")
data = fr.read()
Solution: 2
Use double slash (\\) instead of single slash (\) in the path. The sample code snippet is given below.
fr = open("C:\\Users\\Amal\\PycharmProjects\\data\\out.csv", "r")
data = fr.read()
Solution: 3
Use forward slash (/) instead of using back slash (\) in the path. The sample code snippet is given below.
fr = open("C:/Users/Amal/PycharmProjects/data/out.csv", "r")
data = fr.read()
I hope this solution helps someone 🙂 . Thanks for reading my article.