FileNotFoundError: [Errno 2]

Question:

Synopsis:
How do I read a file in Python?
why must it be done this way?

My problem is that I get the following error:

Traceback (most recent call last):
  File "C:UsersTerminalDesktopwkspcfiletesting.py", line 1, in <module>
    testFile=open("test.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

Which originates from the following code: (that is the entire ‘.py’ file)

testFile=open("test.txt")
print(testFile.read())

“test.txt” is in the same folder as my program. I’m new to Python and do not understand why I am getting file location errors. I’d like to know the fix and why the fix has to be done that way.

I have tried using the absolute path to the file, “C:UsersTerminalDesktopwkspctest.txt”

Other details:

"Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32"
Windows 7, 32 Bit
Asked By: ThisGuy

||

Answers:

Since you are using IDLE(GUI) the script may not be launched from the directory where the script resides. I think the best alternative is to go with something like:

import os.path

scriptpath = os.path.dirname(__file__)
filename = os.path.join(scriptpath, 'test.txt')
testFile=open(filename)
print(testFile.read())

os.path.dirname(__file__) will find the directory where the currently running script resides. It then uses os.path.join to prepend test.txt with that path.

If this doesn’t work then I can only guess that test.txt isn’t actually in the same directory as the script you are running.

Answered By: Michael Petch
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.