5

I'm learning how to open a file in Python, but when I type the path to the file I want to open, a window pops up, saying "(unicode error) 'unicodeescape codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape". It highlights the first of my parentheses. Here's the code:

with open ("C:\Users\Rajrishi\Documents\MyJava\text.txt") as myfile:
    data = myfile.readlines()
print(data)
Adi Inbar
  • 12,097
  • 13
  • 56
  • 69
lilmessi42
  • 313
  • 2
  • 3
  • 13
  • Please include your file. –  Aug 16 '13 at 14:57
  • Does this answer your question? [Why do I get a SyntaxError for a Unicode escape in my file path?](https://stackoverflow.com/questions/18084554/why-do-i-get-a-syntaxerror-for-a-unicode-escape-in-my-file-path) – mkrieger1 Jun 17 '22 at 09:36

1 Answers1

11

One obvious problem is that you're using a normal string, not a raw string. In

open ("C:\Users\Rajrishi\Documents\MyJava\text.txt") 
                                         ^^

the \t is interpreted as a tab character, not a literal backslash, followed by t.

Use one of the following:

open("C:\\Users\\Rajrishi\\Documents\\MyJava\\text.txt") # meh
open(r"C:\Users\Rajrishi\Documents\MyJava\text.txt")     # better
open("C:/Users/Rajrishi/Documents/MyJava/text.txt")      # also possible
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561