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. 


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

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


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.




  • path: The path to the directory.


  • I have a files 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))


Path of current directory: C:\Users\admin\Documents\Visual Studio 2022\testpython\testpython
The files in the directory are: ['test.txt', 'test1.txt', '', '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.


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 =
    print('The content of the file is:', contentStr)
    print("Not a file!")


Not a file!


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 *