-1
"C:\Users\ABHINAV\PycharmProjects\hello project\venv\Scripts\python.exe" "C:/Users/ABHINAV/PycharmProjects/hello project/app48.py"
  File "C:\Users\ABHINAV\PycharmProjects\hello project\app48.py", line 2
    file = open("C:\Users\ABHINAV\Desktop\file22", 'r')
                                                 ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Process finished with exit code 1
deceze
  • 491,798
  • 79
  • 706
  • 853

2 Answers2

0

Change your code to

file = open(r"C:\Users\ABHINAV\Desktop\file22", 'r')
scorpi03
  • 51
  • 3
  • 2
    a single line of code is no good answer, at least explain what was wrong in the original code and what change you suggest, and why – jps May 11 '21 at 07:56
0

The issue here is with your filename, namely that it contains the backslash character \. Standard strings use backslash for escape characters: \n is a newline and not the literal backslash-n for example. You can change this filename into a valid Windows path string by turning it into a raw string: If you see a quoted string preceded by a letter, this is a string that has different properties. An 'r' preceding a string denotes a raw, (almost) un-escaped string. The escape character is backslash, that is why a normal string will not work as a Windows path string. The r prefix on strings stands for "raw strings"

Try adding a r in front of your filename like this:

filename = r"C:\Users\ABHINAV\Desktop\file22"
file = open(filename, 'r')

Alternatively, you could escape the backslashes with additional backslashes:

filename = "C:\\Users\\ABHINAV\\Desktop\\file22"

Or lastly, switch to forward slashes, as Windows will accept them as well:

filename = "C:/Users/ABHINAV/Desktop/file22"
Gustav Rasmussen
  • 3,231
  • 3
  • 19
  • 45
Astros
  • 169
  • 2
  • 10