Search code examples
pythonpycharm

Trouble reading a file in Python (using PyCharm)


I get an error saying "No such file or directory" so I tried adding .txt and it still wont work

I'm learning python and I'm trying to learn how to read files, so I'm was expecting the file to be read using the code written from the file reading

here's the code:

reading = open("Files/reading")
for line in reading:
 print(line)

Solution

  • As already said above - you need to add the file extension and close it at the end. This is provided that your reading.txt text file actually exists in the Files folder.

    reading = open("Files/reading.txt")
    for line in reading:
        print(line)
    reading.close()
    

    Or just drop reading.txt into your project folder and specify a relative path.

    reading = open("reading.txt")
    for line in reading:
        print(line)
    reading.close()
    

    And so, we got that now it is not necessary to specify the path "Files / reading.txt", since the file is located in the same folder as the script.