"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3 [duplicate]
The problem is with the string
"C:\Users\Eric\Desktop\beeline.txt"
Here, \U
in "C:\Users
... starts an eight-character Unicode escape, such as \U00014321
. In your code, the escape is followed by the character 's', which is invalid.
You either need to duplicate all backslashes:
"C:\\Users\\Eric\\Desktop\\beeline.txt"
Or prefix the string with r
(to produce a raw string):
r"C:\Users\Eric\Desktop\beeline.txt"
Typical error on Windows because the default user directory is C:\user\<your_user>
, so when you want to pass this path as a string argument into a Python function, you get a Unicode error, just because the \u
is a Unicode escape. If the next 8 characters after the \u
are not numeric this produces an error.
To solve it, just double the backslashes: C:\\user\\<\your_user>...
This will ensure that Python treats the single backslashes as single backslashes.
Prefixing with 'r'
works very well, but it needs to be in the correct syntax. For example:
passwordFile = open(r'''C:\Users\Bob\SecretPasswordFile.txt''')
No need for \\
here - maintains readability and works well.
With Python 3 I had this problem:
self.path = 'T:\PythonScripts\Projects\Utilities'
produced this error:
self.path = 'T:\PythonScripts\Projects\Utilities'
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 25-26: truncated \UXXXXXXXX escape
the fix that worked is:
self.path = r'T:\PythonScripts\Projects\Utilities'
It seems the '\U' was producing an error and the 'r' preceding the string turns off the eight-character Unicode escape (for a raw string) which was failing. (This is a bit of an over-simplification, but it works if you don't care about unicode)
Hope this helps someone