ENOTEMPTY
Linux / POSIXERRORCommonFile SystemHIGH confidence

Directory Not Empty

Production Risk

Usually a logic error — the code expected an empty directory but found contents.

What this means

ENOTEMPTY (errno 39) is returned by rmdir() when the directory being removed still contains files or subdirectories. rmdir() can only remove empty directories.

Why it happens
  1. 1Calling rmdir() on a directory that still has contents
  2. 2Calling os.rmdir() in Python on a non-empty directory
  3. 3rename() of a directory when the destination directory is non-empty
How to reproduce

Removing a directory that still contains files.

trigger — this will error
trigger — this will error
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

Use shutil.rmtree() to recursively remove a directory and all contents
import shutil
shutil.rmtree('/tmp/mydir')
# Or in shell:
rm -rf /tmp/mydir

Why this works

shutil.rmtree() walks the directory tree and removes all files and subdirectories before removing the directory itself.

What not to do

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.

Sources
Official documentation ↗

Linux Programmer Manual rmdir(2)

rmdir(2)

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Linux / POSIX errors