python-3.x FileNotFoundError:[Errno 2] [duplicate]

1dkrff03  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(87)

此问题在此处已有答案

open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'(11个回答)
How should I write a Windows path in a Python string literal?(5个回答)
1年前关闭。
如何在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'

字符串
它源自以下代码:(即整个“.py”文件)

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


“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

c86crjj0

c86crjj01#

由于您使用的是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__)将找到当前运行的脚本所在的目录,然后使用os.path.join将该路径作为test.txt的前缀。
如果这不起作用,那么我只能猜测test.txt实际上与您正在运行的脚本不在同一个目录中。

相关问题