FileNotFoundError:[Errno 2] [英] FileNotFoundError: [Errno 2]

查看:1531
本文介绍了FileNotFoundError:[Errno 2]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简介:
如何在Python中读取文件?
为什么必须这样做?



我的问题是,我得到以下错误:

  Traceback(最近一次调用的最后一个):
文件C:\ Users \ Terminal \Desktop\wkspc\filetesting.py,第1行, <模块>
testFile = open(test.txt)
FileNotFoundError:[Errno 2]没有这样的文件或目录:'test.txt'

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

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

test.txt与我的程序位于同一个文件夹中。我是Python的新手,不明白为什么我得到文件位置错误。我想知道修复和为什么修复必须这样做。

我已经尝试使用文件的绝对路径,C:\用户\ Terminal \Desktop\wkspc\test.txt

其他详细信息:

<$ p $在$ win32
Windows 7上的Python 3.4.1(v3.4.1:c0e311e010fc,2014年5月18日,10:38:22)[MSC v.1600 32位(Intel)] ,32 Bit


解决方案

该脚本可能不会从脚本所在的目录启动。我认为最好的办法是用类似的方法:

  import os.path 

scriptpath = os.path.dirname(__ file__)
filename = os.path.join(scriptpath,'test.txt')
testFile = open(filename)$ b $ print(testFile.read())

os.path.dirname(__ file __)将找到当前正在运行的脚本所在的目录。然后使用 os.path.join 在该路径前加上 test.txt

如果这不起作用,那么我只能猜测 test.txt 实际上与您正在运行的脚本不在同一个目录中。


Synopsis: How do I read a file in Python? why must it be done this way?

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)

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.

I have tried using the absolute path to the file, "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

解决方案

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:

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.join to prepend test.txt with that path.

If this doesn't work then I can only guess that test.txt isn't actually in the same directory as the script you are running.

这篇关于FileNotFoundError:[Errno 2]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆