Ошибка reading directory 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 Windows path in 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.

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!

Ошибка «No such file or directory» появляется, когда нужный файл отсутствует.

Давайте исключим самое банальное:

1. Файла нет на диске

user@pc1:~$ cat hello.cpp
cat: hello.cpp: No such file or directory

Поскольку отсутствует файл hello.cpp , то выводится ошибка

2. Кириллица в названии

Проверьте, что в названии файла буква «с» не написана кириллицей. Например в расширении «.cpp».

3. Неправильный путь

Пример из Python

data_file= open ("../text.txt",'r')

«../» в общем случае говорит о том, что файл будет искаться на 1 директорию выше, чем файл с кодом.

Если файл лежит в директории с кодом, то следует писать:

data_file= open ("./text.txt",'r')

4. Неправильная битность

Вы можете увидеть ту же ошибку, если пытаетесь запустить например 64-битное приложение на 32-битной Windows

5. Более экзотические причины.

Причина ошибки может быть самой разной, в зависимости от приложения, которое вы используете.

Если это как раз тот случай, напишите о нем в комментариях, в будущем это очень поможет другим.

Нашли опечатку или ошибку? Выделите её и нажмите Ctrl+Enter

Помогла ли Вам эта статья?

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:UsersexpertAppDataLocalProgramsPythonPython310

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

Filenotfounderror Errno 2 no such file or directory is a python error always comes when you are not defining proper path for the file or file does not exist in the directory. In this entire tutorial, you will know how to solve Filenotfounderror Errno 2 no such file or directory in an easy way in different scenarios.

Before going to the various scenarios let’s create a sample CSV file using the panda’s library. The file will contain the name and age of the person. Execute the below line of code to create a person.csv file. It is only for demonstration purposes. You can move to cases if you are already getting the problem.

import pandas as pd
data = {"name":["Sahil","Rob","Maya"],"age":[23,67,45]}
df = pd.DataFrame(data)
df.to_csv("person.csv")

It will save the person.csv file to the current working directory of the project.

Case 1: File Name is Incorrect

If you are reading the CSV file with the incorrect name then you will get this Filenotfounderror Errno 2 with no such file or directory error. For example, instead of reading the person.csv filename, I am reading persons.csv. Then you will get this filenotfounderror.

import pandas as pd
df = pd.read_csv("persons.csv")
print(df)

FileNotfounderror on reading the wrong filename

FileNotfounderror on reading the wrong filename

Solution 

Check the name of the file and write the correct filename with its type.

Case 2: Using the OS Library

Filenotfounderror Errno 2 no such file or directory error also comes when you are using the OS Python library and defining the wrong path. For example, I am passing the wrong path for filename “persons.csv”. It will give me an error.

Solution 

Check the path of the working directory and then define the path.

Case 3: Passing the wrong file name or path for the open() method

The third case is when this error comes when you are reading the file using the open() method and passing the wrong filename.

import csv
with open('persons.csv','r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

FileNotfounderrro on reading the wrong filename using the open() method

FileNotfounderrro on reading the wrong filename using the open() method

Solution :

The solution to this problem, in this case, is very simple. Check the filename of the file you want to open and then pass the exact path for the filename for that file.  To know the current working directory you have to use the os.getcwd(). The error will be solved.

['', 'name', 'age']
['0', 'Sahil', '23']
['1', 'Rob', '67']
['2', 'Maya', '45']

Case 4: Wrong Directory

In most of the cases, Filenotfounderror no such file or directory error comes when you are defining the wrong path for the filename.

import pandas as pd
df = pd.read_csv("/foo/persons.csv")
print(df)

FileNotfounderrro python error due to wrong file path

FileNotfounderrro python error due to wrong file path

Solution

The solution of this case is that if have forgotten the path for the filename then you have to use the OS library. There is a method for finding the path and it is os.getcwd() and then use it with the filename. Execute the following lines of code.

import pandas as pd
import os
cwd = os.getcwd()
df = pd.read_csv(f'{cwd}/person.csv')
print(df)

Now you will get the output.

Solution for FileNotFoundError using the OS Package

Solution for FileNotFoundError using the OS Package

Conclusion

This type of error is mostly annoying to every programmer. They often get this error. These are the cases for various scenarios where its solution is very simple. I hope you have liked this tutorial. If you have any queries then you can contact us for more help.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Понравилась статья? Поделить с друзьями:
  • Ошибка r0206 ford mondeo 3
  • Ошибка read обратилась к памяти как исправить
  • Ошибка r02 на стиральной машине siemens
  • Ошибка read only file system 30
  • Ошибка r02 на стиральной машине bosch