FileNotFoundError: [Errno 2]

Summary: How to read a file in Python? why should it be done that 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' 

What comes from the following code: (this is the entire .py file)

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

"test.txt" is in the same folder as my program. I am new to Python and don't understand why I get errors in the file location. I would like to know how to fix and why the correction should be done this way.

I tried using the absolute path to the file, "C: \ Users \ Terminal \ Desktop \ wkspc \ test.txt"

Other information:

 "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 
+3
source share
1 answer

Since you are using IDLE (GUI), the script may not be run from the directory where the script is located. I think the best alternative is 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 current script is located. He then uses os.path.join to add test.txt with this path.

If this does not work, I can only assume that test.txt is not actually in the same directory as the script.

+11
source

All Articles