FileNotFoundError:[Errno 2]

Thi*_*Guy 3 python file-io python-3.x

概要:如何在Python中读取文件?为什么一定要这样做?

我的问题是我收到以下错误:

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'
Run Code Online (Sandbox Code Playgroud)

其源自以下代码:(即整个'.py'文件)

testFile=open("test.txt")
print(testFile.read())
Run Code Online (Sandbox Code Playgroud)

"test.txt"与我的程序位于同一文件夹中.我是Python的新手,不明白为什么我会收到文件位置错误.我想知道修复以及必须以这种方式完成修复的原因.

我试过使用文件的绝对路径,"C:\ Users\Terminal\Desktop\wkspc\test.txt"

其他详情:

"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
Run Code Online (Sandbox Code Playgroud)

Mic*_*tch 11

由于您使用的是IDLE(GUI),因此可能无法从脚本所在的目录启动脚本.我认为最好的选择是采用以下方式:

import os.path

scriptpath = os.path.dirname(__file__)
filename = os.path.join(scriptpath, 'test.txt')
testFile=open(filename)
print(testFile.read())
Run Code Online (Sandbox Code Playgroud)

os.path.dirname(__file__)将找到当前运行的脚本所在的目录.然后它os.path.join用于前置test.txt该路径.

如果这不起作用,那么我只能猜测它test.txt实际上并不在您运行的脚本所在的目录中.