Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python -How to solve OSError: [Errno 22] Invalid argument [duplicate]

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'
like image 734
Tanishq Trivedi Avatar asked Apr 22 '26 07:04

Tanishq Trivedi


1 Answers

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.

like image 198
M Z Avatar answered Apr 24 '26 21:04

M Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!