FileNotFoundError:[Errno 2] [重复]

问题描述 投票:0回答: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 est.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
python python-3.x file-io
1个回答
13
投票

由于您使用的是 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
实际上与您正在运行的脚本不在同一目录中。

© www.soinside.com 2019 - 2024. All rights reserved.