Ошибка errno 2 no such file or directory

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

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.

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.

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.

Importantly, the CWD is not necessarily where the script is located.

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.

To set the CWD to the folder that contains the current script, determine that path and then set it:

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

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

    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.

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

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

  • 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?.

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

Most Python developers are facing the issue of FileNotFoundError: [Errno 2] No such file or directory: ‘filename.txt’ in Python when they try to open a file from the disk drive. If you are facing the same problem, then you are in the right spot; keep reading. 🧐

FileNotFoundError: [Errno 2] No Such File or Directory is a common error that occurs in Python when you try to access a file that does not exist in the specified location. This error can be caused by a variety of factors, including incorrect file paths and permissions issues.

In this article, we will discuss, What is the file? How to open it? What is FileNotFoundError? When does the No such file or directory error occur? Reasons for No such file or directory error And how to fix it, so let’s get right into the topic without further delay.

Table of Contents
  1. How to Open a File in Python?
  2. What is the FileNotFoundError in Python?
  3. When Does The “FileNotFoundError: [Errno 2] No Such File or Directory” Error Occur?
  4. Reasons for the “FileNotFoundError: [Errno 2] No Such File or Directory” Error in Python
  5. How to Fix the “FileNotFoundError: [Errno 2] No Such File or Directory” Error in Python?

How to Open a File in Python?

Python provides essential methods necessary to manage files by default. We can do most of the file manipulation using a file object. Before we read or write a file, we have to open it. We use Python’s built-in function open() to open a file. This function creates a file object, which supports many other methods, such as tell, seek, read so on.

Syntax

file object = open(file_name [, access_mode][, buffering])

Access mode and buffering are optional in this syntax, but writing the correct file name is mandatory.

What is the FileNotFoundError in Python?

The FileNotFoundError exception raises during file handling. When you try to access a file or directory which doesn’t exist, it will cause a FileNotFoundError exception.

For example, if we write:

Code

myfile = open ("filename.txt", 'r')

Output

The above code will cause the following error message:

FileNotFoundError [Errno 2] No Such File or Directory

If you want to handle this exception properly, write file-handling statements in the try command. 

Suppose you have a doubt your code may raise an error during execution. If you want to avoid an unexpected ending of the program, then you can catch that error by keeping that part of the code inside a try command.

For example, in this code, we see how to handle FileNotFoundError.

Code

Try:

     #open a file in read mode

    myfile = open ("filename.txt",'r')

    print (myfile.read())

    myfile.close()




# In case FileNotFoundError occurs this block will execute 

except FileNotFoundError:

    print ("File is not exists, skipping the reading process...")

Output

How to Fix FileNotFoundError [Errno 2] No Such File or Directory 1

The compiler executes the code given in the try block, and if the code raises a FileNotFoundError exception, then the code mentioned in the except block will get executed. If there is no error, the “else” block will get executed.

When Does The “FileNotFoundError: [Errno 2] No Such File or Directory” Error Occur?

When we try to access a file or directory that doesn’t exist, we face the error No such file or directory.

Code

myfile=open("filename.txt")

Output

Fix FileNotFoundError [Errno 2] No Such File or Directory

Reasons for the “FileNotFoundError: [Errno 2] No Such File or Directory” Error in Python

Here we see some common reasons for no such file or directory error.

  1. Wrong file name
  2. Wrong extension
  3. Wrong case
  4. Wrong path

The following are a few reasons why this error occurs in Python:

  1. Incorrect file path: One of the most common causes of this error is an incorrect file path. Make sure that you are specifying the correct path to the file you are trying to access. You can use the os.path.exists() function to check if the file exists at the specified location.
  2. File permissions: Another common cause of this error is file permissions. If you do not have permission to access the file, you will get this error. To fix this, you can try changing the file permissions using the chmod command.
  3. File encoding: If you are trying to read a file that has a different encoding than what you are expecting, you may get this error. To fix this, you can use the codecs module to specify the correct encoding when you open the file.
  4. File name case sensitivity: Some operating systems, such as Windows, are not case sensitive when it comes to file names, while others, such as Linux and macOS, are. If you are getting this error on a case-sensitive operating system, it could be because the file name you are specifying does not match the actual file name in the correct case. To fix this, make sure that you are specifying the file name in the correct case.
  5. Check for typos: It’s always a good idea to double-check your file path for typos. Even a small typo can cause this error, so ensure you have typed the file path correctly.
  6. Check for hidden files: Some operating systems hide certain files by default. If you try accessing a hidden file, you may get this error. To fix this, you can try accessing the file by specifying the full path, including the "." at the beginning of the file name, which indicates a hidden file.

As Python programmers, we have to take care of these common mistakes. Always double-check the file’s name, extension, case, and location.

We can write file paths in two ways absolute or relative. 

In Absolute file paths, we tell the complete path from the root to the file name, for example, C:/mydir/myfile.txt. 

In relative file paths, we tell the path from the perspective of our current working directory; for example, if our required file is in the current working directory, we have to write “myfile.txt”.

We can check our current working directory with the help of the following code:

Code

import os

current_working_directory = os.getcwd()

print(current_working_directory)

Output

C:\Users\expert\AppData\Local\Programs\Python\Python310

If we want to open a file by just writing its name, we must place it in this directory. Before we move forward to another example of a solution, we have to know about the os built-in module of Python.

The python os module provides several methods that help you perform file-processing operations, such as renaming and deleting files. To utilize this module, you must import it first, and then you can call any related methods.

Now let’s see another example: open a data file and read it.

Code

import os

# store raw string

filepath= r"e:\try.txt"

# Check whether a file exists or not

if os.path.exists(filepath)== True:

    print("file exists")

    #open the file and assign it to file object

    fileobj=open(filepath)

    #print data file on screen

    print(fileobj.read())

#else part will be executed if the file doesn't exist

else:

    print("file doesnt exists")

Output

file exists

This is my data file.

Conclusion

In conclusion, FileNotFoundError: [Errno 2] No Such File or Directory is a common error that occurs in Python when you try to access a file that does not exist in the specified location.

This article shows how to fix 🛠️ the “FileNotFoundError: [Errno 2] No Such File or Directory” error in Python. We discuss all the reasons and their solutions.

We also discuss two essential sources that provide a wide range of utility methods to handle and manipulate files and directories on the Windows operating system.

  1. File object methods
  2. OS object methods

Finally, with the help of this article, you get rid of no such file or directory error.

How can we check our current working directory of Python? Kindly share your current working directory path in the comments below 👇.

Table of Contents
Hide
  1. Python FileNotFoundError: [Errno 2] No such file or directory
  2. Example FileNotFoundError
  3. Misspelled file name
  4. Invalid file path or directory path
  5. Using a relative path
  6. Solution to FileNotFoundError: [Errno 2] No such file or directory

In Python, when you reference a file, it needs to exist. Otherwise, Python will return a FileNotFoundError: [Errno 2] No such file or directory.

In this tutorial, let’s look at what is FileNotFoundError: [Errno 2] No such file or directory error means and how to solve this in your code.

Python will raise FileNotFoundError when you use the OS library and try to read a file or write a file that does not exist using an open() statement.

It is, of course, excluding you are creating a new file and writing content to the file. Any error message which states FileNotFoundError means that Python cannot find the path of the file you are referencing.

Example FileNotFoundError

The below code will list all the files in a specified folder. We will be using the OS module and os.listdir() method to get a list of files in the specified folder.

import os
for f in os.listdir("/etc"):
	print(f)

Output

Traceback (most recent call last):
  File "Main.py", line 2, in <module>
    for f in os.listdir("/etc/test"):
FileNotFoundError: [Errno 2] No such file or directory: '/etc/test'

Now you can see that Python is throwing FileNotFoundError: [Errno 2] No such file or directory since the folder reference is wrong here.

The possible reasons for this error could be as follows.

Misspelled file name

The error will often occur due to misspelled filenames, so providing the correct file name would solve the issue.

Invalid file path or directory path

Sometimes you might give a wrong file path or directory path which does not exist. It usually happens even with the network path when it’s unreachable. So ensure that the file path is correct and if you are placing the file in the network path, make sure it’s reachable and accessible.

Using a relative path

If you use a relative path, the file would be searched in the current working directory and not in the original path. So ensure you give an absolute path of the file to resolve the error.

Solution to FileNotFoundError: [Errno 2] No such file or directory

We will correct our above code by referencing the proper directory where the file exists. This time, we will also use an absolute path instead of a relative path to ensure it’s referencing the correct directory.

import os
for f in os.listdir("C:/Projects/Tryouts/etc"):
	print(f)

Output

python.txt
index.md
Python Data Science Ebook.pdf

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Like any programming language, an error in python occurs when a given code fails to follow the syntax rules. When a code does not follow the syntax, python cannot recognize that segment of code, so it throws an error. Errors can be of different types, such as runtime error, syntax error, logical error, etc. IOError errno 2 no such file or directory is one such type of error. Let us first understand each individual term of the error.

Note : Starting from Python 3.3, IOError is an aliases of OSError

What is IOError?

An IOError is thrown when an input-output operation fails in the program. The common input-output operations are opening a file or a directory, executing a print statement, etc. IOError is inherited from the EnvironmentError. The syntax of IOError is:

IOError : [Error number] ‘Reason why the error occurred’: ‘name of the file because of which the error occurred’

Examples of IOError are :

  • Unable to execute the open() statement because either the filename is incorrect or the file is not present in the specified location.
  • Unable to execute the print() statements because either the disk is full or the file cannot be found
  • The permission to access the particular file is not given.

What is errno2 no such file or directory?

The ‘errorno 2 no such file or directory‘ is thrown when you are trying to access a file that is not present in the particular file path or its name has been changed.

This error is raised either by ‘FileNotFoundError’ or by ‘IOError’. The ‘FileNotFoundError’ raises ‘errorno 2 no such file or directory‘ when using the os library to read a given file or a directory, and that operation fails.

The ‘IOError’ raises ‘errorno 2 no such file or directory‘ when trying to access a file that does not exist in the given location using the open() function.

Handling ‘IOError [errorno 2] no such file or directory’

‘IOError errorno 2 no such file or directory‘ occurs mainly while we are handling the open() function for opening a file. Therefore, we will look at several solutions to solve the above error.

We will check if a file exists, raise exceptions, solve the error occurring while installing ‘requirements.txt,’ etc.

Checking if the file exists beforehand

If a file or a directory does not exist, it will show ‘IOError [errorno 2] no such file or directory’ while opening it. Let us take an example of opening a file named ‘filename.txt’.

The given file does not exist and we shall see what happens if we try to execute it.

Since the above text file does not exist, it will throw the IOError.

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    f = open('filename.txt')
IOError: [Errno 2] No such file or directory: 'filename.txt'

To avoid the above error from being thrown, we will use several methods which will first check if the file exists or not. It will execute the open() function only if the file exists.

We have two modules containing functions for checking if a file exists.

  1. OS Module
  2. Pathlib Module

Using the OS Module

In the os module, there are three functions which can be used:

  • os.path.isfile()
  • os.path.isdir()
  • os.path.exists()

To solve the IOError, we can use either of the above function in a condition statement. We will pass the pathname of the file as an argument to the above functions.

If the file or the directory exists, the function shall return True else False. Bypassing either of the above functions as the conditional statement ensures that python will open a file only if it exists, thus preventing an error from occurring.

We will use os.path.isfile() when we want to check if a file exists or not, os.path.isdir() to check if a directory exists or not and os.path.exists() to check if a path exists or not.

Since we want to check for a file, we can use either the os.path.isfile() function or os.path.exists() function. We shall apply the function to the above example.

import os

path_name = "filename.txt"

if os.path.isfile(path_name):
  print("File exists")
  f = open(path_name)
  #Execute other file operations here
  f.close()
  
else:
  print("File does not exist! IOError has occured")

First, we have imported the os module. Then we have a variable named ‘path_name‘ which stores the path for the file.

We passed the path_name as an argument to the os.path.isfile() function. If the os.path.isfile() function returns a true value. Then it will print “File exists” and execute the other file operations.

If the file does not exist, then it will print the second statement in the else condition. Unlike the previous case, here, it will not throw an error and print the message.

File does not exist! IOError has occured

Similarly, we can also use os.path.exists() function.

Using the pathlib module

The pathlib module contains three functions – pathlib.Path.exists(), pathlib.Path.is_dir() and pathlib.Path.is_file().

We will use pathlib.Path.is_file() in this example. Just like the os module, we will use the function in an if conditional statement.

It will execute the open() function only if the file exists. Thus it will not throw an error.

from pathlib import Path
path_name = "filename.txt"
p = Path(path_name)
if p.is_file():
  print("File exists")
  f = open(path_name)
  #Execute other file operations here
  f.close()
  
else:
  print("File does not exist! IOError has occured")

Since the file does not exist, the output is :

File does not exist! IOError has occured

Using try – except block

We can also use exception handling for avoiding ‘IOError Errno 2 No Such File Or Directory’. In the try block, we will try to execute the open() function.

If the file is present, it will execute the open() function and all the other file operations mentioned in the try block. But, if the file cannot be found, it will throw an IOError exception and execute the except block.

try:
    f = open("filename.txt")
    #Execute other operations
    f.close()
except IOError as io:
    print(io)

Here, it will execute the except block because ‘filename.txt’ does not exist. Instead of throwing an error, it will print the IOError.

[Errno 2] No such file or directory: 'filename.txt'

We can also print a user defined message in the except block.

try:
    f = open("filename.txt")
    #Execute other operations
    f.close()
except IOError:
    print("File does not exist. IOError has occured")

The output will be:

File does not exist. IOError has occured

IOError errno 2 no such file or directory in requirements.txt

Requirements.txt is a file containing all the dependencies in a project and their version details.

Basically, it contains the details of all the packages in python needed to run the project. We use the pip install command to install the requirements.txt file. But it shows the ‘IOError errno 2 no such file or directory’ error.

!pip install -r requirements.txt

The thrown error is:

ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'

To solve the above error, we use the pip freeze command. When we use pip freeze, the output will contain the package along with its version.

The output will be in a configuration that we will use with the pip install command.

pip freeze > requirements.txt

Now, we will try to execute the pip install command again. It will no longer throw errors and all the packages will be installed successfully.

Opening file in ‘w+’ mode

While trying to open a text file, the default mode will be read mode. In that case, it will throw the ‘IOError Errno 2 No Such File Or Directory’ error.

f = open("filename.txt")
f.close()
print("Successful")

The output is:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    f = open("filename.txt")
IOError: [Errno 2] No such file or directory: 'filename.txt'

To solve the error, we can open the file in ‘w+’ mode. This will open the file in both – reading and writing mode. If the file does not exist, it will create a new file, and if the file exists, it will overwrite the contents of the file. This way, it will not throw an error.

f = open("filename.txt", 'w+')
f.close()
print("Successful")

The output is:

Successful

Apart from all the above methods, there are some ways to ensure that the IOError does not occur. You have to ensure that you are giving the absolute path as the path name and not simply the name of the file.

Also, see to that there are no escape sequences in the path name of this file.

For example : In path_name = "C:\name.txt ", it will consider the '\n' from '\name.txt' as an escape sequence. 

So, it will not be able to find the file 'name.txt'.

Also, Read

  • How to Solve “unhashable type: list” Error in Python
  • How to solve Type error: a byte-like object is required not ‘str’
  • Invalid literal for int() with base 10 | Error and Resolution
  • How to Solve TypeError: ‘int’ object is not Subscriptable

What is the difference between FileNotFoundError and IOError

Both the errors occur when you are trying to access a file that is not present in the particular file path, or its name has been changed. The difference between the two is that FileNotFoundError is a type of OSError, whereas IOError is a type of Environment Error.


This sums up everything about IOError Errno 2 No Such File Or Directory. If you have any questions, do let us know in the comments below.

Until then, Keep Learning!

The error FileNotFoundError: [Errno 2] No such file or directory means that Python can’t find the file or directory you are trying to access.

This error can come from calling the open() function or the os module functions that deal with files and directories.

To fix this error, you need to specify the correct path to an existing file.

Let’s see real-world examples that trigger this error and how to fix them.

Error from open() function

Suppose you use Python to open and read a file named output.txt as follows:

with open('output.txt', 'r') as f:
    data = f.read()

Python will look for the output.txt file in the current directory where the code is executed.

If not found, then Python responds with the following error:

Traceback (most recent call last):
  File ...
    with open('output.txt', 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'output.txt'

If the file exists but in a different directory, then you need to specify the correct path to that file.

Maybe the output.txt file exists in a subdirectory like this:

.
├── logs
│   └── output.txt
└── script.py

To access the file, you need to specify the directory as follows:

with open('logs/output.txt', 'r') as f:
    data = f.read()

This way, Python will look for the output.txt file inside the logs folder.

Sometimes, you might also have a file located in a sibling directory of the script location as follows:

.
├── code
│   └── script.py
└── logs
    └── output.txt

In this case, the script.py file is located inside the code folder, and the output.txt file is located inside the logs folder.

To access output.txt, you need to go up one level from as follows:

with open('../logs/output.txt', 'r') as f:
    data = f.read()

The path ../ tells Python to go up one level from the working directory (where the script is executed)

This way, Python will be able to access the logs directory, which is a sibling of the code directory.

Alternatively, you can also specify the absolute path to the file instead of a relative path.

The absolute path shows the full path to your file from the root directory of your system. It should look something like this:

# Windows absolute path
C:\Users\sebhastian\documents\logs

# Mac or Linux
/home/user/sebhastian/documents/logs

Pass the absolute path and the file name as an argument to your open() function:

with open('C:\Users\sebhastian\documents\logs\output.txt', 'r') as f:
    data = f.read()

You can add a try/except statement to let Python create the file when it doesn’t exist.

try:
    with open('output.txt', 'r') as f:
        data = f.read()
except FileNotFoundError:
    print("The file output.txt is not found")
    print("Creating a new file")
    open('output.txt', 'w') as f:
        f.write("Hello World!")

The code above will try to open and read the output.txt file.

When the file is not found, it will create a new file with the same name and write some strings into it.

Also, make sure that the filename or the path is not misspelled or mistyped, as this is a common cause of this error as well.

Error from os.listdir() function

You can also have this error when using a function from the os module that deals with files and directories.

For example, the os.listdir() is used to get a list of all the files and directories in a given directory.

It takes one argument, which is the path of the directory you want to scan:

import os

files = os.listdir("assets")
print(files)

The above code tries to access the assets directory and retrieve the names of all files and directories in that directory.

If the assets directory doesn’t exist, Python responds with an error:

Traceback (most recent call last):
  File ...
    files = os.listdir("assets")
FileNotFoundError: [Errno 2] No such file or directory: 'assets'

The solution for this error is the same. You need to specify the correct path to an existing directory.

If the directory exists on your system but empty, then Python won’t raise this error. It will return an empty list instead.

Also, make sure that your Python interpreter has the necessary permission to open the file. Otherwise, you will see a PermissionError message.

Conclusion

Python shows the FileNotFoundError: [Errno 2] No such file or directory message when it can’t find the file or directory you specified.

To solve this error, make sure you the file exists and the path is correct.

Alternatively, you can also use the try/except block to let Python handle the error without stopping the code execution.

Понравилась статья? Поделить с друзьями:
  • Ошибка esp шкода октавия а7 после снятия клеммы
  • Ошибка error host lookup
  • Ошибка error 01 автомагнитола sony
  • Ошибка err 036
  • Ошибка esp шкода октавия а7 после отключения аккумулятора