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)
2

1 Answer 1

12

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.