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

In Python you can get error like:

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

Which means that you have bad character escape in string. Next example shows how you can get the error:

import json

json_data=open("C:\Users\test.txt").read()
json_obj = json.loads(json_data)

The problem is that \U is considered as a special escape sequence for Python string. In order to resolved you need to add second escape character like:

import json

json_data=open("C:\\Users\\test.txt").read()
json_obj = json.loads(json_data)

Another way to resolved the error is simply by adding r for raw string literals:

import json

json_data=open(r"C:\Users\test.txt").read()
json_obj = json.loads(json_data)

Some best practices shows that using os module is best:

os.path.join(mydir, myfile)

Related Article