OSError: [Errno 39] Directory not empty means you used os.rmdir() on a folder that still has something in it. That function only removes empty directories, by design. To delete a folder and its contents you want shutil.rmtree() — which is powerful enough to deserve some care.
What rmdir does#
import os
os.rmdir("empty_folder") # fine
os.rmdir("has_files") # OSError: Directory not empty
from pathlib import Path
Path("empty_folder").rmdir() # the pathlib equivalent, same restriction
This is deliberate. Removing a directory tree is destructive and irreversible, so the simple function refuses to do it accidentally and you have to reach for a different one on purpose.
Deleting everything#
import shutil
shutil.rmtree("folder_with_contents")
One line, and everything inside is gone — no confirmation, no recycle bin, no undo. That is worth pausing on before you run it.
A safer wrapper#
from pathlib import Path
import shutil
def safe_rmtree(target, base, dry_run=True):
"""Delete a folder, but only if it is inside base."""
target = Path(target).resolve()
base = Path(base).resolve()
if not target.is_relative_to(base):
raise ValueError(f"{target} is outside {base}")
if target == base:
raise ValueError("Refusing to delete the base directory itself")
if not target.is_dir():
raise NotADirectoryError(target)
count = sum(1 for _ in target.rglob("*"))
if dry_run:
print(f"Would delete {target} containing {count} items")
return count
shutil.rmtree(target)
print(f"Deleted {target} and {count} items")
return count
safe_rmtree("uploads/temp/session-42", base="uploads") # shows what it would do
safe_rmtree("uploads/temp/session-42", base="uploads", dry_run=False)
Three protections in there. The path is resolved, so .. cannot escape. It must be inside a base directory you named. And it defaults to a dry run, so the destructive version is something you have to ask for.
Deleting the contents but keeping the folder#
from pathlib import Path
import shutil
def empty_folder(folder):
folder = Path(folder)
for item in folder.iterdir():
if item.is_dir() and not item.is_symlink():
shutil.rmtree(item)
else:
item.unlink()
Useful for a cache or temp directory that other code expects to exist. The symlink check matters — without it, rmtree on a link to somewhere else would follow it.
Deleting selectively#
from pathlib import Path
import time
folder = Path("logs")
cutoff = time.time() - (30 * 24 * 60 * 60) # 30 days
for path in folder.rglob("*.log"):
if path.is_file() and path.stat().st_mtime < cutoff:
print("removing", path)
path.unlink()
# Then remove any directories that are now empty
for path in sorted(folder.rglob("*"), reverse=True):
if path.is_dir() and not any(path.iterdir()):
path.rmdir()
The sorted(..., reverse=True) is doing real work: it processes the deepest directories first, so a folder whose only contents were empty subfolders also gets removed.
Permission errors#
import shutil
import os
import stat
def force_remove(func, path, exc_info):
"""Clear the read-only flag and retry."""
os.chmod(path, stat.S_IWRITE)
func(path)
shutil.rmtree("folder", onexc=force_remove) # Python 3.12+
shutil.rmtree("folder", onerror=force_remove) # older versions
This is mainly a Windows problem — files marked read-only cannot be deleted until the flag is cleared. Git’s internal object files are the usual culprit when removing a cloned repository.
On Windows, PermissionError more often means a file is open in another program. Windows locks open files in a way Linux and macOS do not, so close the editor or terminal sitting in that folder.
import shutil
try:
shutil.rmtree("folder")
except FileNotFoundError:
pass # already gone
except PermissionError as error:
print("In use or read-only:", error.filename)
except OSError as error:
print("Could not remove:", error)
To ignore missing files entirely:
shutil.rmtree("folder", ignore_errors=True)
Be careful with that one — it hides genuine failures as well as harmless ones, so you cannot tell whether the deletion actually worked.
The recycle bin#
python -m pip install send2trash
from send2trash import send2trash
send2trash("folder_with_contents")
This moves the folder to the recycle bin or trash rather than destroying it. For anything a person cares about, it is the right default — and it is a single line’s difference.
Temporary directories that clean themselves#
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as temp:
path = Path(temp)
(path / "working.txt").write_text("scratch data")
# ... do work ...
# Deleted automatically here, even if an exception was raised
If you are creating a folder only to delete it later, this removes the deletion code entirely — and the cleanup happens even when something goes wrong.
A quick reference#
| Task | Use |
|---|---|
| Delete a file | Path(p).unlink() |
| Delete a file, ignore if missing | Path(p).unlink(missing_ok=True) |
| Delete an empty folder | Path(p).rmdir() |
| Delete a folder and contents | shutil.rmtree(p) |
| Empty a folder, keep it | loop over iterdir() |
| Send to the recycle bin | send2trash(p) |
| Temporary, self-cleaning | tempfile.TemporaryDirectory() |
Questions people ask#
Why does rmdir refuse non-empty folders?
To make recursive deletion a deliberate choice rather than an accident. It maps directly to the underlying system call, which has the same restriction for the same reason.
Can I undo shutil.rmtree?
No. It is permanent, with no recycle bin. Use send2trash when recovery might matter.
Why does it fail on Windows but work on Linux?
Windows locks files that are open in another program, and it has a read-only attribute that blocks deletion. The onexc handler above deals with the second; for the first, close whatever has the file open.
How do I delete only empty subfolders?
Walk the tree deepest-first with sorted(folder.rglob("*"), reverse=True) and call rmdir() on any directory with no contents. The order is what makes it work in one pass.
Where to go next#
- Moving files with shutil — the same module, less destructive.
- Python folder and directory management — creating and listing.
- Build a Python file organiser — where these come together.