文件未找到错误:[Errno 2]

2024-05-19 23:02:55 发布

您现在位置:Python中文网/ 问答频道 /正文

概要: 如何用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

Tags: 文件pytesttxtmost错误opencall
1条回答
网友
1楼 · 发布于 2024-05-19 23:02:55

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

相关问题 更多 >