gpt4 book ai didi

open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'(Open()给出FileNotFoundError/ioError:‘[Errno 2]没有这样的文件或目录’)

转载 作者:bug小助手 更新时间:2023-10-28 10:22:21 27 4
gpt4 key购买 nike



I am trying to open the file recentlyUpdated.yaml from my Python script. But when I try using:

我正在尝试从我的Python脚本打开文件recentlyUpdated.yaml。但当我尝试使用时:


open('recentlyUpdated.yaml')

I get an error that says:

我收到一个错误,内容是:


IOError: [Errno 2] No such file or directory: 'recentlyUpdated.yaml'

Why? How can I fix the problem?

为什么?我怎样才能解决这个问题?


更多回答

Make sure you can see all the file extensions in File Explorer... As I learnt the hard way.

确保您可以在文件资源管理器中查看所有文件扩展名...就像我吃了不少苦头一样。

Using PyCharm? ============= Mark the folder where the .csv file locates as "source root" -> right-click on the folder and "Mark the directory as" and select "Source Root". Also, check the working directory in the Run/Debug Configuration -> Run menu -> Edit Configuration -> Select Python file in left pane -> Make sure Working Directory is the root folder of your project [jetbrains.com/help/pycharm/… [1]: jetbrains.com/help/pycharm/…

使用PyCharm?=将.csv文件所在的文件夹标记为“源根目录”->右击该文件夹,“将目录标记为”,然后选择“源根目录”。此外,在运行/调试配置->运行菜单->编辑配置->在左侧窗格中选择PYTHON文件->确保工作目录是项目的根文件夹[jetbrains.com/Help/PYCharm/…]中检查工作目录[1]:jetbrains.com/Help/pycharm/…

For me, the problem was that my files were symlinked. The underlying data was missing after copying a folder to a different computer were the data did not exist. This taught me to always check in the terminal what's going on.

对我来说,问题是我的文件是符号链接的。如果数据不存在,则在将文件夹复制到另一台计算机后,基础数据会丢失。这教会了我总是在航站楼检查正在发生的事情。

See also What exactly is current working directory?

另请参见什么是当前工作目录?

优秀答案推荐


  • Ensure the file exists (and has the right file extension): use os.listdir() to see the list of files in the current working directory.

  • Ensure you're in the expected directory using os.getcwd().

    (If you launch your code from an IDE, you may be in a different directory.)

  • You can then either:

    • Call os.chdir(dir) where dir is the directory containing the file. Then, open the file using just its name, e.g. open("file.txt").

    • Specify an absolute path to the file in your open call.



  • Use a raw string (r"") if your path uses backslashes, like
    so: dir = r'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.




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.

  • 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().


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.

如果您尝试打开(‘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.txt位于C:\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. 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脚本的位置是一种常见的误解,但事实并非如此。相对文件路径始终相对于当前工作目录,并且当前工作目录不必是您的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. Double-check your file's extension.

    由于Windows不显示已知的文件扩展名,有时当您认为文件名为file.yaml时,它实际上名为file.yaml.yaml。仔细检查文件的扩展名。




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()函数检查是否至少可以看到该文件。



Try it like this:

像这样试一试:



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


Possibly, you closed the 'file1'.

Just use 'w' flag, that create new file:

可能是你关闭了“文件1”。只需使用'w'标志,创建新文件:



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



mode is an optional string that specifies the mode in which the file
is opened. It defaults to 'r' which means open for reading in text
mode. Other common values are 'w' for writing (truncating the file if
it already exists)...




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

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



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).

路径这个词的意思和它听起来的一样。它显示了需要采取的步骤,进入和离开文件夹,以找到一个文件。路径上的每一步都是一个文件夹名称,特殊名称。(表示当前文件夹)或特殊名称。(这意味着返回/退出到父文件夹)。


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. (On Windows there are also UNC paths, which are necessarily absolute. Most people will never have to worry about these.)

在Windows上,以路径分隔符或驱动器号后跟路径分隔符(如C:/foo)开头的路径是绝对路径。(在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). At the command line, Linux and Mac use a common CWD across all drives. (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.

相对路径是相对于所谓的当前工作目录(以下简称为CWD)而言的。在命令行中,Linux和Mac在所有驱动器上使用通用的CWD。(整个文件系统有一个公共的“根”,并且可能包括多个物理存储设备。)Windows略有不同:它会记住每个驱动器的最新CWD,并具有在驱动器之间切换的单独功能,从而恢复那些旧的CWD值。


Each process (this includes terminal/command windows) has its own CWD. When a program is started from the command line, it will get the CWD that the terminal/command process was using. 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.

每个进程(包括终端/命令窗口)都有自己的CWD。当一个程序从命令行启动时,它将获得终端/命令进程正在使用的CWD。当程序从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. Each IDE has its own rules that control the initial CWD; check the documentation for details.

可以使用os.getcwd检查脚本的CWD,并使用os.chdir对其进行修改。每个IDE都有自己的规则来控制初始CWD;有关详细信息,请查看文档。


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". This is wrong. That file is actually - normally - at C:/Users/name/Desktop/foo.txt (replacing name with the current user's username). It could instead be elsewhere, if Windows is configured to put it elsewhere. To find the path to the desktop in a portable way, see How to get Desktop location?.

    文件的路径可能与预期不符的原因有很多。例如,有时人们认为Windows上的C:/foo.txt意味着“桌面上名为foo.txt的文件”。这是不对的。该文件实际上通常位于C:/USERS/NAME/Desktop/foo.txt(用当前用户的用户名替换NAME)。相反,如果Windows配置为将其放在其他地方,它可能会放在其他地方。要以便携方式找到桌面路径,请参见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).

    在相对路径中错误计算..S,或者在路径中不适当地重复文件夹名称也是很常见的。以编程方式构建路径时要特别小心。最后,请记住..已在根目录(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 (e.g. 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. That part of the path must be explicitly converted to the actual path, using os.path.expanduser. See Why am I forced to os.path.expanduser in python? and os.makedirs doesn't understand "~" in my path.

    另一个常见的问题是,当前用户主目录的特殊~快捷方式在Python程序中指定的绝对路径中不起作用。必须使用os.path.expanduser将路径的该部分显式转换为实际路径。请参见为什么我被强制使用python中的os.path.expanduser?Os.make dis不理解我的路径中的“~”。



  • Keep in mind that os.listdir will give only the file names, not paths. Trying to iterate over a directory listed this way will only work if that directory is the current working directory.

    请记住,os.listdir将只给出文件名,而不给出路径。仅当该目录是当前工作目录时,尝试迭代以这种方式列出的目录才会起作用。



  • It's also important to make sure of the actual file name. Windows has an option to hide file name extensions in the 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. 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. (The Linux/Mac equivalent is ls, of course; but the problem should not arise there in the first place.)

    确保实际的文件名也很重要。Windows具有在图形用户界面中隐藏文件扩展名的选项。如果您在窗口中看到foo.txt,则可能是文件的实际名称是foo.txt.txt或其他名称。您可以在您的设置中禁用此选项。您还可以使用命令行验证文件名;dir将告诉您有关文件夹中内容的真相。(当然,Linux/Mac的等价物是ls;但问题一开始就不应该出现在那里。)



  • Backslashes in ordinary strings are escape sequences. This causes problems when trying to a backslash as the path separator on Windows. However, using backslashes for this is not necessary, and generally not advisable. See How should I write a Windows path in a Python string literal?.

    普通字符串中的反斜杠是转义序列。在Windows上尝试使用反斜杠作为路径分隔符时,这会导致问题。然而,使用反斜杠来实现这一点是不必要的,而且通常也不可取。请参见How Shout I Ware a Windows Path in a Python字符串文字?



  • When trying to create a new file using a file mode like w, the path to the new file still needs to exist - i.e., all the intervening folders. See for example Trying to use open(filename, 'w' ) gives 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.

    当尝试使用像w这样的文件模式创建新文件时,新文件的路径仍然需要存在--即所有中间文件夹。例如,请参见尝试使用OPEN(文件名,‘w’)会给出ioerror:[Errno 2]如果目录不存在,则没有这样的文件或目录。还要记住,新文件名必须是有效的。特别是,尝试在文件名中插入MM/DD/YYYY格式的日期是行不通的,因为/S将被视为路径分隔符。





If is VSCode see the workspace. If you are in other workspace this error can rise

如果是VSCode,请参见工作区。如果您在其他工作区中,则可能会出现此错误



Make sure that all the folders in the path for the file exist.


I was getting this error because it was non-obvious to me if the folder was being created or not because, in theory, a function called in the code should've done that.

我收到这个错误是因为我不清楚是否正在创建文件夹,因为从理论上讲,代码中调用的函数应该做到这一点。


import os

file_path = input('Input file path')
dir_path = os.path.dirname(file_path)

os.makedirs(dir_path, exist_ok=True)

with open(file_path) as file:
file.write("Written!")



In OP's case, he's only reading the file so it should exist in the path he provided. It might be common that we forget the w flag for the open function (e.g. open('/path/to/file', 'w')) and end up getting this error.

在OP的例子中,他只是读取文件,所以它应该存在于他提供的路径中。我们经常会忘记打开函数的w标志(例如OPEN(‘/Path/to/file’,‘w’)),结果得到这个错误。



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.

如果它类似于-->/文件夹/子文件夹/文件-->计算机将搜索根目录中的文件夹。


If its something like--> ./folder/subfolder/file --> Computer will search for folder in current working directory.

如果它类似于-->./文件夹/子文件夹/文件-->计算机将在当前工作目录中搜索文件夹。



If you are using IDE like VScode, make sure you have opened the IDE from the same directory where you have kept the file you want to access.

如果您使用的是与VScode类似的IDE,请确保您已从保存要访问的文件的同一目录中打开了IDE。


For example, if you want to access file.txt which is inside the Document, try opening the IDE from Document by right clicking in the directory and clicking "Open with "

例如,如果要访问文档中的file.txt,请尝试从文档中打开IDE,方法是在目录中右键单击,然后单击“打开方式”



(for Pycharm)

(适用于PyCharm)


Pycharm has a built-in "Active Directory" setting


You may receive this error when changing the folder name because this setting isn't updated. To fix this error within Pycharm, select "Edit Configurations" (Top right of the window next to the Run button).

更改文件夹名称时可能会收到此错误,因为此设置未更新。要在PyCharm中修复此错误,请选择“编辑配置”(窗口右上角紧挨着Run按钮)。


Picture of "Edit Configurations"


Then change both the script path (just in case you haven't already) and the working directory folder.

然后更改脚本路径(以防您尚未更改)和工作目录文件夹。


enter image description here



One (out of many) possible failure scenario:

一个(多个)可能的故障情况:



  • if the target file is a symlink and you got the reference e.g. via os.scandir(), os.listdir() etc and then tried to call .stat() on a broken symlink then the stat() call will be attempted against the non-existent symlink target, rather than the symlink itself.


By default .stat() is called with .stat(*, follow_symlinks=True); use .stat(follow_symlinks=False) to prevent following (broken) symlinks.

默认情况下,使用.stat(*,Follow_symlink=True)调用.stat();使用.stat(Follow_symlink=False)来防止跟随(断开)符号链接。


更多回答

On linux, home dir paths like ~/ does not work too. So you need to use /home/user/temp/file.txt instead of ~/temp/file.txt.

在Linux上,像~/这样的主目录路径也不起作用。因此,您需要使用/home/user/temp/file.txt而不是~/temp/file.txt。

@Radek Yeah, ~ is a shorthand in a shell, not the filesystem. If you want Python to expand it, use os.path.expanduser() or pathlib.Path.expanduser().

@Radek是的,~是外壳中的缩写,而不是文件系统。如果希望让Python将其展开,请使用os.path.expanduser()或pathlib.Path.expanduser()。

os.chdir changes the global state of the program and might introduce errors at other parts of the script. I wouldn't recommend this.

Os.chdir更改程序的全局状态,并可能在脚本的其他部分引入错误。我不推荐这样做。

it cant seem to recognize any file paths on my computer. Is there any way I can search for a file? @sshekar

它似乎无法识别我计算机上的任何文件路径。有什么方法可以搜索文件吗?@sshekar

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com