Python FileNotFoundError: [错误 2]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25924720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
FileNotFoundError: [Errno 2]
提问by ThisGuy
Synopsis: How do I read a file in Python? why must it be done this way?
概要:如何在 Python 中读取文件?为什么必须这样做?
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)
源自以下代码:(即整个“.py”文件)
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.
“test.txt”与我的程序在同一个文件夹中。我是 Python 新手,不明白为什么会出现文件位置错误。我想知道修复方法以及为什么必须以这种方式进行修复。
I have tried using the absolute path to the file, "C:\Users\Terminal\Desktop\wkspc\test.txt"
我尝试使用文件的绝对路径,“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
采纳答案by Michael Petch
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:
由于您使用的是 IDLE(GUI),因此可能无法从脚本所在的目录启动脚本。我认为最好的选择是使用以下方法:
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.jointo prepend test.txtwith that path.
os.path.dirname(__file__)将找到当前正在运行的脚本所在的目录。然后它os.path.join用于预先test.txt添加该路径。
If this doesn't work then I can only guess that test.txtisn't actually in the same directory as the script you are running.
如果这不起作用,那么我只能猜测它test.txt实际上与您正在运行的脚本不在同一目录中。

