IsADirectoryError
IsADirectoryError: [Errno 21] Is a directory: '/tmp'
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
data = f.read()
IsADirectoryError: [Errno 21] Is a directory: '/tmp'What causes this error
A file operation like open() or os.remove() was called on a path that is a directory, not a regular file.
How to fix it
Check whether the path is a file or directory using `os.path.isfile()` or `pathlib.Path.is_file()` before performing the operation. Use `os.rmdir()` or `shutil.rmtree()` for directories.
Code that causes this error
with open("/tmp") as f:
data = f.read()Fixed code
from pathlib import Path
p = Path("/tmp")
if p.is_file():
data = p.read_text()
else:
print(f"{p} is a directory, not a file")About IsADirectoryError
An IsADirectoryError is raised when a file operation is requested on a directory. This is a subclass of OSError and most often appears when using `open()` on a path that turns out to be a directory rather than a regular file. It can also occur when trying to remove a directory with `os.remove()` (which only works on files — use `os.rmdir()` or `shutil.rmtree()` for directories).
The error is straightforward to fix: verify whether the path is a file or directory before performing the operation, and use the appropriate function for the entity type. The `pathlib.Path` class provides convenient `.is_file()` and `.is_dir()` methods for these checks, and `os.path.isfile()` / `os.path.isdir()` serve the same purpose in the os module.
Common scenarios
Opening files with incorrect or relative paths
Reading files that have been moved, renamed, or deleted
Writing to directories instead of files or vice versa
Working with file streams that have been closed prematurely