简体   繁体   English

open() 给出 FileNotFoundError/IOError: Errno 2 No such file or directory

[英]open() gives FileNotFoundError/IOError: Errno 2 No such file or directory

For some reason my code is having trouble opening a simple file:出于某种原因,我的代码无法打开一个简单的文件:

This is the code:这是代码:

file1 = open('recentlyUpdated.yaml')

And the error is:错误是:

IOError: [Errno 2] No such file or directory: 'recentlyUpdated.yaml'
  • 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.我试过移动文件,给open()文件的完整路径,但似乎都不起作用。
  • Make sure the file exists: use os.listdir() to see the list of files in the current working directory确保文件存在:使用os.listdir()查看当前工作目录中的文件列表
  • 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)确保您位于您认为与os.getcwd()所在的目录中(如果您从 IDE 启动代码,您很可能位于不同的目录中)
  • 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.调用os.chdir(dir)dir是文件所在的文件夹,然后像以前一样使用其名称打开文件。
    • Specify an absolute path to the file in your open call.open调用中指定文件的绝对路径。
  • Remember to use a raw string if your path uses backslashes, like so: dir = r'C:\Python32'如果您的路径使用反斜杠,请记住使用原始字符串,如下所示: dir = r'C:\Python32'
    • If you don't use raw-string, you have to escape every backslash: 'C:\\User\\Bob\\...'如果您不使用原始字符串,则必须转义每个反斜杠: 'C:\\User\\Bob\\...'
    • Forward-slashes also work on Windows 'C:/Python32' and do not need to be escaped.正斜杠也适用于 Windows 'C:/Python32' ,不需要转义。

Let me clarify how Python finds files:让我澄清一下 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.绝对路径是以计算机的根目录开头的路径,例如C:\Python\scripts如果您在 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 calling os.getcwd() .您可以通过调用os.getcwd()查看 Python 的当前工作目录。

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.如果您尝试执行open('sortedLists.yaml') ,Python 将看到您正在向其传递相对路径,因此它将在当前工作目录中搜索文件。

Calling os.chdir() will change the current working directory.调用os.chdir()将更改当前工作目录。

Example: Let's say file.txt is found in C:\Folder .示例:假设file.txtC:\Folder中找到。

To open it, you can do:要打开它,您可以执行以下操作:

os.chdir(r'C:\Folder')
open('file.txt') # relative path, looks inside the current working directory

or或者

open(r'C:\Folder\file.txt') # absolute path

Most likely, the problem is that you're using a relative file path to open the file, but the current working directory isn't set to what you think it is.最有可能的问题是您使用相对文件路径来打开文件,但当前工作目录未设置为您认为的那样。

It's a common misconception that relative paths are relative to the location of the python script, but this is untrue.相对路径相对于 python 脚本的位置是一个常见的误解,但这是不正确的。 Relative file paths are always relative to the current working directory, and the current working directory doesn't have to be the location of your python script.相对文件路径总是相对于当前工作目录,并且当前工作目录不一定是你的 python 脚本的位置。

You have three options:你有三个选择:

  • Use an absolute path to open the file:使用绝对路径打开文件:

     file = open(r'C:\path\to\your\file.yaml')
  • Generate the path to the file relative to your python script:生成相对于您的 python 脚本的文件路径:

     from pathlib import Path script_location = Path(__file__).absolute().parent file_location = script_location / 'file.yaml' file = file_location.open()

    (See also: How do I get the path and name of the file that is currently executing? ) (另请参阅: 如何获取当前正在执行的文件的路径和名称?

  • Change the current working directory before opening the file:在打开文件之前更改当前工作目录:

     import os os.chdir(r'C:\path\to\your\file') file = open('file.yaml')

Other common mistakes that could cause a "file not found" error include:其他可能导致“找不到文件”错误的常见错误包括:

  • Accidentally using escape sequences in a file path:在文件路径中意外使用转义序列:

     path = 'C:\Users\newton\file.yaml' # Incorrect! The '\n' in 'Users\newton' is a line break character!

    To avoid making this mistake, remember to use raw string literals for file paths:为避免犯此错误,请记住对文件路径使用原始字符串文字

     path = r'C:\Users\newton\file.yaml' # Correct!

    (See also: Windows path in Python ) (另请参阅: Python 中的 Windows 路径

  • Forgetting that Windows doesn't display file extensions:忘记 Windows 不显示文件扩展名:

    Since Windows doesn't display known file extensions, sometimes when you think your file is named file.yaml , it's actually named file.yaml.yaml .由于 Windows 不显示已知的文件扩展名,因此有时当您认为您的文件名为file.yaml时,它实际上名为file.yaml.yaml Double-check your file's extension.仔细检查文件的扩展名。

The file may be existing but may have a different path.该文件可能存在,但可能具有不同的路径。 Try writing the absolute path for the file.尝试编写文件的绝对路径。

Try os.listdir() function to check that atleast python sees the file.尝试使用os.listdir()函数来检查至少 python 是否可以看到该文件。

Try it like this:试试这样:

file1 = open(r'Drive:\Dir\recentlyUpdated.yaml')

Possibly, you closed the 'file1'.可能,您关闭了“file1”。
Just use 'w' flag, that create new file:只需使用 'w' 标志,即创建新文件:

file1 = open('recentlyUpdated.yaml', 'w')

mode is an optional string that specifies the mode in which the file is opened. mode是一个可选字符串,它指定打开文件的模式。 It defaults to 'r' which means open for reading in text mode.它默认为“r”,表示以文本模式打开以供阅读。 Other common values are 'w' for writing (truncating the file if it already exists)...其他常用值是 'w' 用于写入(如果文件已经存在,则截断文件)......

(see also https://docs.python.org/3/library/functions.html?highlight=open#open ) (另见https://docs.python.org/3/library/functions.html?highlight=open#open

If is VSCode see the workspace.如果是 VSCode,请查看工作区。 If you are in other workspace this error can rise如果您在其他工作区,此错误可能会上升

Understanding absolute and relative paths了解绝对路径和相对路径

The term path means exactly what it sounds like.路径一词的意思正是它听起来的样子。 It shows the steps that need to be taken, into and out of folders, to find a file.它显示了查找文件所需的步骤,进出文件夹。 Each step on the path is either a folder name, the special name .路径上的每个步骤要么是文件夹名称,要么是特殊名称. (which means the current folder), or the special name .. (which means to go back/out into the parent folder). (表示当前文件夹)或特殊名称.. (表示将 go 退回/退出到父文件夹)。

The terms absolute and relative also have their usual English meaning.绝对相对这两个术语也有它们通常的英语含义。 A relative path shows where something is relative to some start point;相对路径显示某物相对于某个起点的位置; an absolute path is a location starting from the top.绝对路径是从顶部开始的位置。

Paths that start with a path separator, or a drive letter followed by a path separator (like C:/foo ) on Windows, are absolute. Windows 上以路径分隔符或驱动器号后跟路径分隔符(如C:/foo )开头的路径是绝对路径。 (On Windows there are also UNC paths , which are necessarily absolute. Most people will never have to worry about these.) (在 Windows 上也有UNC 路径,它们必须是绝对的。大多数人永远不必担心这些。)

Paths that directly start with a file or folder name, or a drive letter followed directly by the file or folder name (like C:foo ) on Windows, are relative. Windows 上直接以文件或文件夹名称开头的路径,或直接后跟文件或文件夹名称(如C:foo )的驱动器号的路径是相对的。

Understanding the "current working directory"了解“当前工作目录”

Relative paths are "relative to" the so-called current working directory (hereafter abbreviated CWD).相对路径是“相对于”所谓的当前工作目录(以下简称 CWD)。 At the command line, Linux and Mac use a common CWD across all drives.在命令行中,Linux 和 Mac 在所有驱动器上使用通用 CWD。 (The entire file system has a common "root", and may include multiple physical storage devices.) Windows is a bit different: it remembers the most recent CWD for each drive, and has separate functionality to switch between drives, restoring those old CWD values. 整个文件系统有一个共同的“根”,并且可能包括多个物理存储设备。) Windows 有点不同:它记住每个驱动器的最新 CWD,并具有在驱动器之间切换的单独功能,恢复那些旧的 CWD价值观。

Each process (this includes terminal/command windows) has its own CWD.每个进程(包括终端/命令窗口)都有自己的 CWD。 When a program is started from the command line, it will get the CWD that the terminal/command process was using.从命令行启动程序时,它将获得终端/命令进程正在使用的 CWD。 When a program is started from a GUI (by double-clicking a script, or dragging something onto the script, or dragging the script onto a Python executable) or by using an IDE, the CWD might be any number of things depending on the details.当程序从 GUI 启动时(通过双击脚本,或将某些内容拖到脚本上,或将脚本拖到 Python 可执行文件上)或使用 IDE,CWD 可能是任意数量的东西,具体取决于详细信息.

Importantly, the CWD is not necessarily where the script is located.重要的是,CWD不一定是脚本所在的位置。

The script's CWD can be checked using os.getcwd , and modified using os.chdir .可以使用os.getcwd检查脚本的 CWD,并使用os.chdir进行修改 Each IDE has its own rules that control the initial CWD;每个 IDE 都有自己的规则来控制初始 CWD; check the documentation for details.检查文档以获取详细信息。

To set the CWD to the folder that contains the current script, determine that path and then set it:要将 CWD 设置为包含当前脚本的文件夹,请确定该路径,然后进行设置:

os.chdir(os.path.dirname(os.path.abspath(__file__)))

Verifying the actual file name and path验证实际文件名和路径

  • There are many reasons why the path to a file might not match expectations.文件路径可能与预期不符的原因有很多。 For example, sometimes people expect C:/foo.txt on Windows to mean "the file named foo.txt on the desktop" .例如,有时人们期望C:/foo.txt表示“桌面上名为foo.txt的文件” This is wrong.这是错误的。 That file is actually - normally - at C:/Users/name/Desktop/foo.txt (replacing name with the current user's username).该文件实际上 -通常- 在C:/Users/name/Desktop/foo.txt (用当前用户的用户名替换name )。 It could instead be elsewhere , if Windows is configured to put it elsewhere.如果 Windows 配置为将其放置在其他位置,则它可能位于其他位置。 To find the path to the desktop in a portable way, see How to get Desktop location?要以便携式方式查找桌面的路径,请参阅如何获取桌面位置? . .

    It's also common to mis-count .. s in a relative path, or inappropriately repeat a folder name in a path.在相对路径中错误计数..或在路径中不恰当地重复文件夹名称也很常见。 Take special care when constructing a path programmatically.以编程方式构建路径时要特别小心。 Finally, keep in mind that .. will have no effect while already in a root directory ( / on Linux or Mac, or a drive root on Windows).最后,请记住..已经在根目录(Linux 或 Mac 上的/或 Windows 上的驱动器根目录)中时将不起作用。

    Take even more special care when constructing a path based on user input.在基于用户输入构建路径时要特别小心。 If the input is not sanitized, bad things could happen (eg allowing the user to unzip a file into a folder where it will overwrite something important, or where the user ought not be allowed to write files).如果输入没有被清理,可能会发生不好的事情(例如,允许用户将文件解压缩到一个文件夹中,它会覆盖一些重要的东西,或者用户不应该被允许写入文件)。

  • Another common gotcha is that the special ~ shortcut for the current user's home directory does not work in an absolute path specified in a Python program.另一个常见的问题是当前用户主目录的特殊~快捷方式在 Python 程序中指定的绝对路径中不起作用 That part of the path must be explicitly converted to the actual path, using os.path.expanduser .该部分路径必须使用os.path.expanduser显式转换为实际路径。 See Why am I forced to os.path.expanduser in python?请参阅为什么我被迫在 python 中使用 os.path.expanduser? and os.makedirs doesn't understand "~" in my path .并且os.makedirs 在我的路径中不理解“~”

  • Keep in mind that os.listdir will give only the file names, not paths .请记住, os.listdir只会给出文件名,而不是路径 Trying to iterate over a directory listed this way will only work if that directory is the current working directory.仅当该目录是当前工作目录时,尝试遍历以这种方式列出的目录才有效。

  • It's also important to make sure of the actual file name.确保实际文件名也很重要。 Windows has an option to hide file name extensions in the GUI. Windows 具有在 GUI 中隐藏文件扩展名的选项。 If you see foo.txt in a window, it could be that the file's actual name is foo.txt.txt , or something else.如果您在 window 中看到foo.txt ,则文件的实际名称可能是foo.txt.txt或其他名称。 You can disable this option in your settings.您可以在设置中禁用此选项。 You can also verify the file name using the command line;您还可以使用命令行验证文件名; dir will tell you the truth about what is in the folder. dir将告诉您有关文件夹中内容的真相。 (The Linux/Mac equivalent is ls , of course; but the problem should not arise there in the first place.) (Linux/Mac 的等价物当然是ls ;但问题不应该首先出现在那里。)

  • Backslashes in ordinary strings are escape sequences.普通字符串中的反斜杠是转义序列。 This causes problems when trying to a backslash as the path separator on Windows.当尝试将反斜杠用作 Windows 上的路径分隔符时,这会导致问题。 However, using backslashes for this is not necessary, and generally not advisable .但是,没有必要为此使用反斜杠,通常也不建议这样做。 See Windows path in Python .请参阅Python 中的 Windows 路径

  • When trying to create a new file using a file mode like w , the path to the new file still needs to exist - ie, all the intervening folders.当尝试使用w之类的文件模式创建新文件时,新文件的路径仍然需要存在 - 即所有中间文件夹。 See for example Trying to use open(filename, 'w' ) gives IOError: [Errno 2] No such file or directory if directory doesn't exist .参见示例Trying to use open(filename, 'w' ) 给出 IOError: [Errno 2] No such file or directory if directory doesn't exist Also keep in mind that the new file name has to be valid.另请记住,新文件名必须有效。 In particular, it will not work to try to insert a date in MM/DD/YYYY format into the file name, because the / s will be treated as path separators.特别是,尝试在文件名中插入MM/DD/YYYY格式的日期是行不通的,因为/ s 将被视为路径分隔符。

I had the same problem.我有同样的问题。 My problem was about file name.我的问题是关于文件名。 I changed the file name from ASVspoof2017_train.trn.txt to ASV.txt and the error removed !我将文件名从ASVspoof2017_train.trn.txt 更改ASV.txt并删除了错误!

Check the path that has been mentioned, if it's absolute or relative.检查已经提到的路径,是绝对的还是相对的。

If its something like--> /folder/subfolder/file -->Computer will search for folder in root directory.如果它类似于--> /folder/subfolder/file --> 计算机将在根目录中搜索文件夹。

If its something like--> ./folder/subfolder/file --> Computer will search for folder in current working directory.如果它类似于--> ./folder/subfolder/file --> 计算机将在当前工作目录中搜索文件夹。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python open() 给出“FileNotFoundError: [Errno 2] No such file or directory:”,但文件存在 - Python open() gives "FileNotFoundError: [Errno 2] No such file or directory:", but the file exists 打开 FileNotFoundError: [Errno 2] 没有这样的文件或目录: - with open FileNotFoundError: [Errno 2] No such file or directory: IOError:[Errno 2]没有尝试打开文件的文件或目录 - IOError: [Errno 2] No such file or directory trying to open a file 尝试使用 open(filename, 'w' ) 会导致 IOError: [Errno 2] 如果目录不存在,则没有这样的文件或目录 - Trying to use open(filename, 'w' ) gives IOError: [Errno 2] No such file or directory if directory doesn't exist IOError:[Errno 2]没有这样的文件或目录 - IOError: [Errno 2] No such file or directory IOError:[Errno 2]没有这样的文件或目录? - IOError: [Errno 2] No such file or directory? FileNotFoundError [Errno 2] 没有这样的文件或目录: - FileNotFoundError [Errno 2] No such file or directory: FileNotFoundError: [Errno 2] 没有这样的文件或目录? - FileNotFoundError: [Errno 2] No such file or directory? FileNotFoundError:[Errno 2]没有这样的文件或目录: - FileNotFoundError: [Errno 2] No such file or directory: 在 python 中打开文件会出现错误 IOError: [Errno 2] No such file or directory: '' on MAC - Opening a file in python gives the error IOError: [Errno 2] No such file or directory: '' on MAc
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM