Operation expected a file, but got a directory
A subclass of `OSError`, raised when a file operation (like `open()` or `os.remove()`) is requested on a directory. These operations are only valid for files.
- 1Trying to `open()` and read from a path that points to a directory.
- 2Attempting to delete a directory using `os.remove()` instead of `os.rmdir()`.
- 3Passing a directory path to a function that expects a file path.
This error is triggered by attempting to open a directory for reading as if it were a file.
import os
# Create a directory to demonstrate
if not os.path.exists("my_test_dir"):
os.mkdir("my_test_dir")
try:
with open("my_test_dir", "r") as f: # Trying to open a directory
content = f.read()
except IsADirectoryError as e:
print(f"Caught IsADirectoryError: {e}")
finally:
os.rmdir("my_test_dir") # Clean up
expected output
Caught IsADirectoryError: [Errno 21] Is a directory: 'my_test_dir'
Fix 1
Check if the path is a file before opening
WHEN A given path could be either a file or a directory.
import os
path = "some_path" # Could be a file or a directory
if os.path.isfile(path):
with open(path, "r") as f:
# process file
pass
elif os.path.isdir(path):
print(f"{path} is a directory, not a file.")
Why this works
`os.path.isfile()` specifically checks if the path points to a file, allowing you to avoid attempting file operations on directories.
Fix 2
Use the correct function for directories
WHEN You need to perform an operation on a directory, such as deleting it.
import os
import shutil
dir_path = "my_empty_dir"
if os.path.exists(dir_path):
# os.remove(dir_path) # -> Would raise IsADirectoryError
os.rmdir(dir_path) # Correct for empty directories
non_empty_dir = "my_non_empty_dir"
if os.path.exists(non_empty_dir):
shutil.rmtree(non_empty_dir) # Correct for non-empty directories
Why this works
Python's `os` and `shutil` modules provide separate functions for file operations (`os.remove`) and directory operations (`os.rmdir`, `shutil.rmtree`). Using the correct function for the target object type is essential.
with open("/etc") as f:
pass # IsADirectoryError: Is a directorytry:
with open(path) as f:
data = f.read()
except IsADirectoryError:
print(f"{path} is a directory, not a file")import os
if os.path.isfile(path):
with open(path) as f:
data = f.read()✕ Catching `IsADirectoryError` and just ignoring it
This error points to a fundamental misunderstanding in your code about what it's operating on. Ignoring it means your program is failing to process the data it was supposed to.
cpython/Objects/exceptions.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev