2
sav = []
def fileKeep(sav):
    classA = open("classA", "r")
    for line in classA:
        sav.append(line.split())
    file.close()
    return
fileKeep(sav)

This is the end of my code. I get a File Not Found error that I do not get anywhere else, even though I have used the file nearer to the beginning of the code as well. Any assistance is welcome, thanks.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
zeldor
  • 101
  • 1
  • 9
  • 1
    Does your file have an extension? Is it in the same folder where this script is being executed? If not, then it's normal that you have that error. – nbro Jan 28 '15 at 17:48
  • The file is in the same folder, with no extension. The same file has worked previously in my code – zeldor Jan 28 '15 at 17:52
  • @Rinzler: Python opens relative path in the *current working directory*, not the directory of the script. – Martijn Pieters Jan 28 '15 at 18:38
  • @MartijnPieters Oh, sorry, correct. – nbro Jan 28 '15 at 18:49
  • Does this answer your question? [open() gives FileNotFoundError/IOError: Errno 2 No such file or directory](https://stackoverflow.com/questions/12201928/open-gives-filenotfounderror-ioerror-errno-2-no-such-file-or-directory) – Karl Knechtel Sep 05 '22 at 10:44

1 Answers1

2

You code is assuming that the current working directory is the same as the directory your script lives in. It is not an assumption you can make.

Use an absolute path for your data file. You can base it on the absolute path of your script:

import os.path

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class_a_path = os.path.join(BASE_DIR, "classA")

classA = open(class_a_path)

You can verify what the current working directory is with os.getcwd() if you want to figure out where instead you are trying to open your data file.

Your function could be simplified to:

def fileKeep(sav):
    with open(class_a_path) as class_:
        sav.extend(l.split() for l in class_)

provided class_a_path is a global.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I still get the same error: classA = open(class_a_path) FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Alexander\\Documents\\Python\\classA' even when i make it global – zeldor Jan 28 '15 at 19:02
  • @zeldor: and you are 100% certain that `C:\Users\Alexander\Documents\Python\classA` exists and is readable? What does Windows Explorer shows is in that directory? Are you certain you are not hiding the extensions on those files? – Martijn Pieters Jan 28 '15 at 19:10
  • As I said previously I am sure that there are no hidden extensions as the same file worked in code earlier on in my program. C:\Users\Alexander\Documents\Python\classA definitely exists – zeldor Jan 28 '15 at 19:40
  • Ok guys thanks for the help, I apparently missed out the .txt - I feel stupid, didn't realize what you had been saying. Thanks – zeldor Jan 28 '15 at 19:55