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
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)
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 main.py and a directory ‘testpython’.
getcwd()function to get the current directory path.
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.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.
I need to check if ‘testpython’ is a regular file in Python.
- Open ‘testpython’
- Use the
os.path.isfile()method in the
if...elseblock 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!")
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:
- Python csv “TypeError: a bytes-like object is required, not ‘str’”
- Could not find a version that satisfies the requirement cv2 (from versions: ) No matching distribution found for cv2
My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.
Name of the university: HHAU
Programming Languages: C++, Python, Java