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'
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.