the full guide

Deleting files and folders

Python deletes files with os.remove() or Path.unlink(), empty folders with os.rmdir(), and folders with their contents using shutil.rmtree(). None of these use the recycle bin, so deletion is permanent.

4 min Intermediate

What you need: The earlier topics of this module.

Definition

Python deletes files with os.remove() or Path.unlink(), empty folders with os.rmdir(), and folders with their contents using shutil.rmtree(). None of these use the recycle bin, so deletion is permanent.

In simple words

Unlike pressing delete on your desktop, there's no undo here. So always check what you're about to delete.

Why it matters

Scripts often clean up temporary files. A wrong path in a delete command is one of the fastest ways to lose real work.

How it works

In code

deleting.py
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as folder:
    file = Path(folder) / "old.txt"
    file.write_text("delete me", encoding="utf-8")
    print("Before:", file.exists())

    file.unlink()
    print("After:", file.exists())

    file.unlink(missing_ok=True)     # no error when already gone
    print("Second delete raised no error")

Output

Before: True
After: False
Second delete raised no error

Common mistakes

  • Deleting without checking that the path is what you think it is.
  • Using os.rmdir on a folder with files in it, which raises an error.

Check yourself

Question 1

1. Which deletes a folder and everything in it?

Question 2

2. Do these go to the recycle bin?

Summary

  • unlink for files, rmdir for empty folders, rmtree for full ones.
  • There's no undo, so check first.

Finished reading?

Sources: The Python Tutorial, python.org