Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'invalid argument' error opening file (and not reading file)

Tags:

python

file

I am trying to write code that takes 2 numbers in a text file and then divides them, showing the answer as a top heavy fraction. I have gotten the fractions part to work when I am inputting my own values in the program, but i cannot get the program to recognise the text file. I have tried putting them in the same directory and putting the full system path of the file, but nothing so far has worked. right now I am just trying to get the contents of the file to print.

with open('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt','w') as f:
    for line in f:
        for word in line.split():
            print(word)      

I will then assign the 2 values to x and y, but I get this error:

Traceback (most recent call last):
File "C:\Python34\divider.py", line 2, in <module>
open('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt','w')
OSError: [Errno 22] Invalid argument:'C:\\ProgramData\\Microsoft\\Windows\\Startmenu\\Programs\\Python 3.4\topheavy.txt'
like image 553
Sawyer Avatar asked Oct 30 '14 20:10

Sawyer


People also ask

What is invalid argument error in Python?

The invalid argument error is a WebDriver error that occurs when the arguments passed to a command are either invalid or malformed. Invalid argument errors can be likened to TypeError s in JavaScript, in that they can occur for a great many APIs when the input value is not of the expected type or malformed in some way.

What is file open error?

This error occurs when there is a problem with the filename being opened. There are two known causes, the file location being invalid or the current user lacking permission.

How to solve OSError errno 22 invalid argument?

The OSError : [errno22] invalid argument error has been thrown because of the same reason as before. Here also, python fails to recognize the backslash symbol. On replacing backslash with forward slash, the error will be resolved.


1 Answers

open('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt','w')
OSError: [Errno 22] Invalid argument:'C:\\ProgramData\\Microsoft\\Windows\\Startmenu\\Programs\\Python 3.4\topheavy.txt'

Two things:

  1. When working with paths that contain backslashes, you either need to use two backslashes, or use the r'' form to prevent interpreting of escape sequences. For example, 'C:\\Program Files\\...' or r'C:\Program Files\...'.
  2. Your error shows this: \\Startmenu\\. It appears that a space is missing between "Start" and "menu", despite the fact that the open line seems to have the right path.

Note: that the \topheavy.txt in your path is probably getting converted to <tab>opheavy.txt too. That's why there aren't two backslashes in front of it in the traceback.

like image 157
John Szakmeister Avatar answered Oct 04 '22 15:10

John Szakmeister