How To Solve “IsADirectoryError: [Errno 21] Is A Directory” In Python?

IsADirectoryError: [Errno 21] Is a directory in Python

Python allows you to work with files quickly, but you have to be careful because working with files requires you to follow the operating system’s rules. One of the errors that you can get is “IsADirectoryError: [Errno 21] is a directory” error.

What causes the “IsADirectoryError: [Errno 21] is a directory” error in Python?

This error happens when you perform an invalid operation on a directory. You interact with a directory as if it were a file such as calling the open() function. 

Example:

We have a main.py file and a ‘testpython’ directory. We will execute the following statements in main.py:

file = open("testpython", "r")
str = file.read()
print('The content of the file is:', str)

Output:

IsADirectoryError: [Errno 21] Is a directory: 'testpython'

The problem is that ‘testpython’ is a directory, so my access to the open() function will fail.

How to solve this error?

Use the listdir() method

We will use the listdir() method to read the names of the directory entries in the given path.

Syntax:

os.listdir(path)

Parameters:

  • path: The path to the directory.

Example:

  • I have a files main.py and a directory ‘testpython’.
  • Use getcwd() function to get the current directory path.
  • Use listdir() to output the names of the entries in the ‘testpython’ directory.
import os

path = os.getcwd()
print("Path of current directory:", path)
print("The files in the directory are: ", os.listdir(path))

Output:

Path of current directory: C:\Users\admin\Documents\Visual Studio 2022\testpython\testpython
The files in the directory are: ['test.txt', 'test1.txt', 'testpython.py', 'testpython.pyproj']

Check if the file is a regular file or not

I would use the os.path.isfile() method inside an if...else block to check if the file is a regular file or not.

Example:

I need to check if ‘testpython’ is a regular file in Python.

  • Open ‘testpython’
  • Use the os.path.isfile() method in the if...else block to check if ‘testpython’ exists.
  • If ‘testpython’ is a regular file, read the contents of the file; otherwise output “Not a file!”.
import os

open_file = 'testpython'

if os.path.isfile(open_file):
    file = open("testpython", "r")
    contentStr = file.read()
    print('The content of the file is:', contentStr)
else:
    print("Not a file!")

Output:

Not a file!

Summary

If you have any questions about the “IsADirectoryError: [Errno 21] is a directory” error in Python, please leave a comment below. I will answer your questions. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *