Open file error with Python open file

I learn how to open a file in Python, but when I type the path to the file I want to open, a window appears saying: "(unicode error)" Unicodeescape codec cannot decode bytes at 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) 
+4
source share
1 answer

One obvious problem is that you are using a regular string, not a raw string. IN

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

\t interpreted as a tab character, not a literal backslash, and then t .

Use one of the following actions:

 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 
+11
source

Source: https://habr.com/ru/post/1497454/


All Articles