[Solved] IOError errno 2 no such file or directory

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.

f = open('filename.txt')

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

FAQ’s on IOError Errno 2 No Such File Or Directory

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!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments