Why do I get a SyntaxError for a Unicode escape in my file path? [duplicate]

You need to use a raw string, double your slashes or use forward slashes instead:

r'C:\Users\expoperialed\Desktop\Python'
'C:\\Users\\expoperialed\\Desktop\\Python'
'C:/Users/expoperialed/Desktop/Python'

In regular Python strings, the \U character combination signals an extended Unicode codepoint escape.

You can hit any number of other issues, for any of the other recognised escape sequences, such as \a, \t, or \x.

Note that as of Python 3.6, unrecognized escape sequences can trigger a DeprecationWarning (you’ll have to remove the default filter for those), and in a future version of Python, such unrecognised escape sequences will cause a SyntaxError. No specific version has been set at this time, but Python will first use SyntaxWarning in the version before it’ll be an error.

If you want to find issues like these in Python versions 3.6 and up, you can turn the warning into a SyntaxError exception by using the warnings filter error:^invalid escape sequence .*:DeprecationWarning (via a command line switch, environment variable or function call):

Python 3.10.0 (default, Oct 15 2021, 22:25:32) [Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import warnings
>>> '\expoperialed'
'\\expoperialed'
>>> warnings.filterwarnings('default', '^invalid escape sequence .*', DeprecationWarning)
>>> '\expoperialed'
<stdin>:1: DeprecationWarning: invalid escape sequence '\e'
'\\expoperialed'
>>> warnings.filterwarnings('error', '^invalid escape sequence .*', DeprecationWarning)
>>> '\expoperialed'
  File "<stdin>", line 1
    '\expoperialed'
    ^^^^^^^^^^^^^^^
SyntaxError: invalid escape sequence '\e'

Leave a Comment