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

created at May 24, 2021, 3:12 p.m. views: 0

Description

When you meet this error, it means there are some problem with your Unicode escaping.

For example, you are using a path like:

test.load_data("C:\path\to\your\file")

However, \ in python is an escape, python won't treat C:\path\to\your\file as a path.

or you will get an error like:

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

Solutions

there are at least two solutions for this problem

1 replacing “\” with “/”

C:/path/to/your/file

now, python will know its a path.

2 adding an “r” prefix to the path

this method is quite simple, and you may see many people have chosen this way:

test.load_data(r"C:\path\to\your\file")

the r prefix will make python treat the following string as a raw, un-escaped string. The escape character is backslash, that is why a normal string will not work as a Windows path string.

References

https://discuss.python.org/t/what-does-r-define-in-file-path/3646

Please log in to leave a comment.