pythontypeerror

'str' object integer error for os.open in Python


I'm a fairly new programmer, and trying to do my first file read.

My aim is to strip unnecessary line breaks from text in a .txt file copied from a PDF, but I cannot get the file to open.

I already swapped the slash direction, as the \ for windows directories was interpreted as an exception character in the filename string

My question is:

Why does this code:

import os
my_file = os.open('C:/Users/USER/Documents/20 Programming/Code institute 5 day coding challenge.txt', 'r')
my_file.close()

give this error?

TypeError: 'str' object cannot be interpreted as an integer

Here is the full console output:

"C:\Users\USER\Documents\20 Programming\untitled\venv\venv\Scripts\python.exe" "C:\Users\USER\Documents\20 Programming\untitled\remove carriage returns if no capital letter next.py" 
Traceback (most recent call last):
  File "C:\Users\USER\Documents\20 Programming\untitled\remove carriage returns if no capital letter next.py", line 21, in <module>
    my_file = os.open('C:/Users/USER/Documents/20 Programming/Code institute 5 day coding challenge.txt', 'r')
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'str' object cannot be interpreted as an integer

I've tried googling the error and had no joy, as this error isn't discussed in relation to open() as far as I can find.

I'm expecting the file to open so I can read the results

Edit: Thanks everyone. I've now replaced os.open() with just open(). I've now got a different error (file not found) so I'll try to tackle that next... (note this is not a new question!)


Solution

  • As others have mentioned, I am not sure why you are using os.open(). As for the issue you are facing, you can simply use

    with open("file.txt", "r") as file:
        # read the contents of the file and remove all line breaks
        contents = file.read().replace('\n', '')
    
    # print the contents of the file without line breaks
    print(contents)
    

    The reason you are gettng the error is because os.open() expects an integer constant as the second argument where you are passing a string (r).The correct code would be something like

    import os
    my_file = os.open('C:/Users/USER/Documents/20 Programming/Code institute 5 day coding challenge.txt', os.O_RDONLY)
    os.close(my_file)
    

    example call os.open(file, flags[, mode]);

    os.O_RDONLY is the flag sayng open it for reading only it represents an integer value. You can look up the docs for any function. For e.g https://www.tutorialspoint.com/python/os_open.htm