8

I am learning about file objects in python but whenever i try to open file it shows the following error.

I have already checked that file is in same directory and it exists this error occurs only if i name my file as test if i use any other name then it works fine here's my CODE

f = open('C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')

here's the ERROR

  Traceback (most recent call last):
  File "C:/Users/Tanishq/Desktop/question.py", line 1, in <module>
  f = open('C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
  OSError: [Errno 22] Invalid argument: 'C:\\Users\\Tanishq\\Desktop\\python   
  tutorials\test.txt'
Pranav Choudhary
  • 2,726
  • 3
  • 18
  • 38
Tanishq Trivedi
  • 101
  • 1
  • 1
  • 7
  • 1
    You need to escape all of the `\ `s in your string or use a [raw string](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals) (that is, `r'...'`) – 0x5453 Jul 31 '20 at 15:38
  • Place an `r` before the string and remove the double backslash. – Klaus D. Jul 31 '20 at 15:39
  • 1
    You have to either escape all backslashes (`'C:\\\\Users\\Tanishq\\Desktop\\python tutorials\\test.txt'`) or use the raw string literal (`r'C:\\Users\Tanishq\Desktop\python tutorials\test.txt'`). – Gevorg Davoian Jul 31 '20 at 15:39
  • Thanks...it helped – Tanishq Trivedi Jul 31 '20 at 18:14

1 Answers1

12

Your issue is with backslashing characters like \T :

Try:

f = open(r'C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')

Python uses \ to denote special characters. Therefore, the string you provided does not actually truly represent the correct filepath, since Python will interpret \Tanishq\ differently than the raw string itself. This is we we place the r in front of it. This lets Python know that we do indeed want to use the raw string and to treat \ as a normal character.

M Z
  • 4,571
  • 2
  • 13
  • 27