0

Python read files

Hello, i am learning python at the moment and just learned how to open and read files. So I wanted to try it but if i do this i get an unicode error. Heres my code: lol = open ("C:\Users\user\Desktop\file_test.txt", "r") cont = lol.read() print (cont) lol.close() Or: lol = open ("C:\Users\user\Desktop\file_test.txt") print (lol.read) lol.close() No matte how i get this error: SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape And its pointing on the character after "......file_test.txt" Please help. Thank you!

5th Feb 2021, 8:10 PM
Domme 1
3 Respostas
+ 4
It's most likely seeing the backslashes as escape characters. To get it to see them as regular backslashes, you can escape the backslashes with another backslash like "C:\\Users\\user\\Desktop\\file_test.txt" or You may be able to use a raw string r"C:\Users\user\Desktop\file_test.txt"
5th Feb 2021, 8:24 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Thanks man it worked. Wow i didnt know the raw string. Its very cool, just put a "r" to the begining and everything works.
5th Feb 2021, 8:50 PM
Domme 1