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

31,443

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.

Share:
31,443

Related videos on Youtube

Tanishq Trivedi
Author by

Tanishq Trivedi

Currently i m a high school student and i am learning python, i also know about relational databases (mysql), html and css. i m trying to develop expertise in python, django, mysql. i m also learning about algorithms and data structures.

Updated on April 10, 2022

Comments

  • Tanishq Trivedi
    Tanishq Trivedi 7 months

    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'
    
    • 0x5453
      0x5453 over 2 years
      You need to escape all of the \ s in your string or use a raw string (that is, r'...')
    • Klaus D.
      Klaus D. over 2 years
      Place an r before the string and remove the double backslash.
    • Gevorg Davoian over 2 years
      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').
    • Tanishq Trivedi
      Tanishq Trivedi over 2 years
      Thanks...it helped