2

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:\Users\Terminal\Desktop\wkspc\filetesting.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:\Users\Terminal\Desktop\wkspc\test.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
ThisGuy
  • 31
  • 1
  • 1
  • 4
  • 3
    Seems caused by different reasons. 1. For using `"test.txt"`, how do you invoke your python script? 2. For using the full path, have you avoided escaping the characters (e.g. by using `r"C:\Users\Terminal\Desktop\wkspc\test.txt"` notice the `r`) – starrify Sep 19 '14 at 01:00
  • Can you show us the command you use to launch python with your script? – Michael Petch Sep 19 '14 at 01:09
  • 1
    If you want to use Python to load `test.txt` from the same directory as the python script you need to be in that directory when you launch python. My only guess is that you are launching the python script from somewhere else – Michael Petch Sep 19 '14 at 01:15
  • I launch the "IDLE (Pytho GUI)" that was installed with Python and from there I open my program and run it. (file->open->etc.) – ThisGuy Sep 19 '14 at 01:28

1 Answers1

13

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.

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
  • 1
    This worked, Thank you! Hopefully, I can veer away from this fix once I'm more educated. – ThisGuy Sep 19 '14 at 01:48
  • Normally you specify the full path of the file name as starrify mentioned (what they suggested would have worked too) and that would have resolved the issue. This code will work no matter how the script is launched and from where (different path). – Michael Petch Sep 19 '14 at 01:52