Python open()提供FileNotFoundError/IOError:Errno 2没有这样的文件或目录 [英] Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory
本文介绍了Python open()提供FileNotFoundError/IOError:Errno 2没有这样的文件或目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于某种原因,我的代码无法打开简单文件:
For some reason my code is having trouble opening a simple file:
这是代码:
file1 = open('recentlyUpdated.yaml')
错误是:
IOError: [Errno 2] No such file or directory: 'recentlyUpdated.yaml'
- 自然地,我检查了文件名是否正确.
- 我尝试过移动文件,为
open()
提供文件的完整路径,但似乎没有任何作用. - Naturally I checked that this is the correct name of the file.
- I have tried moving around the file, giving
open()
the full path to the file and none of it seems to work. - 确保文件存在:使用
os.listdir()
查看当前工作目录中的文件列表 - 使用
os.getcwd()
确保您位于自己认为的目录中(如果从IDE启动代码,则很可能位于其他目录中) - 然后您可以:
- 调用
os.chdir(dir)
,其中dir
是文件所在的文件夹找到文件,然后像以前一样使用文件名打开文件. - 在您的
open
调用中指定文件的绝对路径. - Make sure the file exists: use
os.listdir()
to see the list of files in the current working directory - Make sure you're in the directory you think you're in with
os.getcwd()
(if you launch your code from an IDE, you may well be in a different directory) - You can then either:
- Call
os.chdir(dir)
,dir
being the folder where the file is located, then open the file with just its name like you were doing. - Specify an absolute path to the file in your
open
call. - 如果您不使用原始字符串,则必须转义每个反斜杠:
'C:\\ User \\ Bob \\ ...'
- 正斜杠在Windows
'C:/Python32'
上也可以使用,不需要转义. - If you don't use raw-string, you have to escape every backslash:
'C:\\User\\Bob\\...'
- Forward-slashes also work on Windows
'C:/Python32'
and do not need to be escaped. - 绝对路径是从计算机的根目录开始的路径,例如,如果您使用的是Windows,则为"C:\ Python \ scripts ..".
- 相对路径是不以您计算机的根目录开头的路径,而是相对于称为
工作目录
的东西的路径.您可以通过调用os.getcwd()
来查看Python的当前工作目录. - An absolute path is a path that starts with your computer's root directory, for example 'C:\Python\scripts..' if you're on Windows.
- A relative path is a path that does not start with your computer's root directory, and is instead relative to something called the
working directory
. You can view Python's current working directory by callingos.getcwd()
.
让我澄清一下Python如何查找文件:
Let me clarify how Python finds files:
如果您尝试执行
open('sortedLists.yaml')
,Python将看到您正在向其传递相对路径,因此它将在当前工作目录中搜索文件.调用os.chdir
将更改当前工作目录.If you try to do
open('sortedLists.yaml')
, Python will see that you are passing it a relative path, so it will search for the file inside the current working directory. Callingos.chdir
will change the current working directory.示例:假设在
C:\ Folder
中找到了file.txt
.Example: Let's say
file.txt
is found inC:\Folder
.要打开它,您可以执行以下操作:
To open it, you can do:
os.chdir(r'C:\Folder') open('file.txt') #relative path, looks inside the current working directory
或
open(r'C:\Folder\file.txt') #full path
这篇关于Python open()提供FileNotFoundError/IOError:Errno 2没有这样的文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Call
- 调用
推荐答案
查看全文