Directory Not Empty
Production Risk
Usually a logic error — the code expected an empty directory but found contents.
ENOTEMPTY (errno 39) is returned by rmdir() when the directory being removed still contains files or subdirectories. rmdir() can only remove empty directories.
- 1Calling rmdir() on a directory that still has contents
- 2Calling os.rmdir() in Python on a non-empty directory
- 3rename() of a directory when the destination directory is non-empty
Removing a directory that still contains files.
import os
os.rmdir('/tmp/mydir') # /tmp/mydir has files in it
# OSError: [Errno 39] Directory not empty: '/tmp/mydir'expected output
OSError: [Errno 39] Directory not empty: '/tmp/mydir'
Fix
Use shutil.rmtree() to recursively remove a directory and all contents
WHEN When you intend to remove the directory and all its contents
import shutil
shutil.rmtree('/tmp/mydir')
# Or in shell:
rm -rf /tmp/mydirWhy this works
shutil.rmtree() walks the directory tree and removes all files and subdirectories before removing the directory itself.
✕ Use rm -rf / or rm -rf /* without verifying the path
Recursive deletion with an incorrect path is unrecoverable. Always verify the path before recursive deletion.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev