Thuta Learning
Python
IntermediateProgrammingBeginner

Python Delete Files

PythonLesson 3325 min

What you'll walk away with

  • Tell apart what Path.unlink(), os.remove(), Path.rmdir() and shutil.rmtree() delete
  • Explain why missing_ok=True or try/except beats checking exists() first
  • Reject paths containing ../ with resolve() and is_relative_to()
  • Write a cleanup function with a dry-run mode

Explain it simply

Explain it simply

Deleting a file from Python is not like pressing Delete on your desktop. The file does not go to the Recycle Bin or the Trash; it is gone immediately and for good. There is no undo button.

So whenever you write deleting code, think like a surgeon: confirm exactly which file you are about to remove, make sure it sits inside the place you allow, and, when you can, show a list of what would be deleted before deleting anything. One line of code can remove a single file or an entire folder tree.

Problem → Why → Solution

The problem: one user-supplied name deletes an important file

A web app lets users delete their own export files. The code joins the file name the user sent with the exports folder and deletes the result. Sending "report.csv" works fine. Then someone sends "../config/database.ini", the ../ climbs out of the exports folder, and the app's database config is deleted. The exists() check protects nothing, because that file really does exist.

delete_export.py
import os

EXPORTS = "/srv/app/exports"

def delete_export(filename):                  # filename comes from the user
    path = os.path.join(EXPORTS, filename)     # "../config/database.ini" escapes
    if os.path.exists(path):
        os.remove(path)                        # permanent: no Recycle Bin
        return "deleted"
    return "not found"

Why does this happen?

os.path.join() only glues strings together; it never checks where the result points. ".." means the parent folder, so the path ends up outside exports. To prevent this security bug, called path traversal, convert the path to its real absolute form with resolve() and check that it still sits inside the allowed folder.

Core concept: what, where, and what if it is gone

Python's deleting functions differ by what kind of thing they can remove. Calling the wrong one and getting an error is the lucky outcome; the unlucky one is calling shutil.rmtree() with the wrong path.

FunctionRemovesNotes
Path.unlink() / os.remove()One file (or a symlink)OSError for a folder
Path.rmdir() / os.rmdir()One empty folderOSError if anything is inside
shutil.rmtree()A folder and everything in itMost dangerous; asks nothing

Path.unlink() and os.remove() do the same job. Calling unlink() on a folder raises an OSError subclass such as IsADirectoryError or PermissionError, depending on the operating system. Unlinking a symlink removes only the link itself, never the file it points to. A missing file raises FileNotFoundError, and since Python 3.8 unlink(missing_ok=True) accepts that case quietly.

The popular pattern if os.path.exists(path): os.remove(path) has two problems. First, if another process deletes the file between the check and the removal, os.remove() still crashes with FileNotFoundError; this is called a check-then-act race (TOCTOU). Second, exists() only says whether a file is there, not whether you should delete it. The more Pythonic way is to attempt the deletion and handle the exception (EAFP: "easier to ask forgiveness than permission"). The question of where you are allowed to delete is answered by resolve() and is_relative_to(), shown in the deeper section.

To delete many files at once, you search with a pattern. Path.glob("*.tmp") looks in one folder only, while rglob("*.tmp") descends into every subfolder. A pattern like "*" or the wrong folder variable can match far more than you expect, so print or count the matches before deleting any of them. Taking the list first with sorted() or list(), rather than deleting while the glob is still being iterated, also keeps the logic easy to follow.

Mental model: aim, check the fence, then cut
  1. Resolve the path to its real form
  2. Check it is inside the allowed folder
  3. Check it is a file, not a folder
  4. Delete; handle FileNotFoundError

exists() answers "is it there?", never "should I delete it?".

General pattern

python
from pathlib import Path

target = (allowed_root / name).resolve()
if not target.is_relative_to(allowed_root.resolve()):
    raise ValueError("path escapes the allowed folder")

target.unlink(missing_ok=True)   # one file; no error if already gone
empty_folder.rmdir()             # only works on an EMPTY folder

First resolve the path and check it stays under the allowed root. Then delete the file with unlink(); missing_ok=True means no error if it is already gone. rmdir() only removes an empty folder.

Example: deleting a file and a folder

This example works only inside a temporary folder, so it can never touch real files on your machine. It creates a file, deletes it, then deletes it again to show what missing_ok changes. Finally it watches rmdir() refuse a folder that is not empty.

delete_basics.py
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    root = Path(tmp)
    dummy = root / "dummy_file.txt"
    dummy.write_text("Temp file.", encoding="utf-8")
    print(f"'{dummy.name}' created: {dummy.exists()}")

    dummy.unlink()                       # delete one file
    print(f"'{dummy.name}' deleted: {not dummy.exists()}")

    dummy.unlink(missing_ok=True)        # already gone: no error
    try:
        dummy.unlink()                   # without missing_ok it raises
    except FileNotFoundError:
        print("Second unlink() raised FileNotFoundError")

    exports = root / "exports"
    exports.mkdir()
    (exports / "old.csv").write_text("id,total\n", encoding="utf-8")
    try:
        exports.rmdir()                  # rmdir() only removes EMPTY folders
    except OSError:
        print("rmdir() refused: exports is not empty")
    for item in exports.iterdir():
        item.unlink()
    exports.rmdir()
    print(f"exports removed: {not exports.exists()}")

Code breakdown

  1. Line 10dummy.unlink() # delete one file

    Path.unlink() is the same as os.remove(dummy). The file vanishes immediately; it does not go to the Recycle Bin.

  2. Line 13dummy.unlink(missing_ok=True) # already gone: no error

    The file is gone, but missing_ok=True makes this a no-op. It is ideal for cleanup code whose goal is simply "the file should not exist afterwards", with no exists() check needed.

  3. Lines 14-17except FileNotFoundError:

    Without missing_ok, a missing file raises FileNotFoundError. When the file really should exist, that error is useful: it warns you about a bug.

  4. Lines 22-25exports.rmdir() # rmdir() only removes EMPTY folders

    old.csv is still inside exports, so rmdir() refuses with OSError. That refusal is a safety feature that keeps you from wiping a folder's contents by accident.

  5. Lines 26-28for item in exports.iterdir():

    After each file inside is deleted, rmdir() succeeds. If the folder held subfolders too, this simple loop would not be enough and you would need shutil.rmtree().

You should see
'dummy_file.txt' created: True
'dummy_file.txt' deleted: True
Second unlink() raised FileNotFoundError
rmdir() refused: exports is not empty
exports removed: True

Never let a path escape the allowed folder

This safe_delete() fixes the bug from the problem section. resolve() works out .. parts and symlinks and returns the real path. Then is_relative_to() (Python 3.9+) checks that the path is still under the root. It also refuses to target the root itself (".") and never deletes anything that is not a regular file.

safe_delete.py
import tempfile
from pathlib import Path


def safe_delete(root: Path, relative: str) -> str:
    base = root.resolve()
    target = (base / relative).resolve()
    if target == base or not target.is_relative_to(base):
        return f"refused: {relative}"          # outside the allowed folder
    if not target.is_file():
        return f"not a file: {relative}"
    target.unlink()
    return f"deleted: {relative}"


with tempfile.TemporaryDirectory() as tmp:
    exports = Path(tmp) / "exports"
    exports.mkdir()
    (exports / "old.csv").write_text("id\n", encoding="utf-8")
    (Path(tmp) / "secret.txt").write_text("keep me\n", encoding="utf-8")
    for name in ["old.csv", "../secret.txt", ".", "missing.csv"]:
        print(safe_delete(exports, name))
    print("secret.txt still there:", (Path(tmp) / "secret.txt").exists())

Always guard shutil.rmtree()

shutil.rmtree(path) deletes a whole folder, every file and subfolder inside it, without asking. If path is an empty string or the wrong variable, it can remove far more than you meant. Before calling it, resolve the path and check it is under the root, just as safe_delete() does.

In real projects

Where this shows up in real projects

On servers, cleanup jobs run every day to delete export files, temporary uploads and old logs that are more than 30 days old. Such jobs usually carry three safeguards: they only search inside one designated folder, they restrict themselves to a pattern such as *.csv, and a --dry-run flag shows what would be deleted first. An engineer checks the dry-run output before the real run.

Features that delete user data often move files to an archive folder first (Path.rename() or shutil.move()), or mark them as deleted in a database and purge them days later, so a user's mistake can still be undone. Every deletion is also written to an audit log recording who deleted what, and when.

Common mistakes

Common mistakes

1. Deleting an unchecked user-supplied path

A name containing "../" can reach outside the allowed folder. Resolve the path, check it with is_relative_to(root), and refuse anything that fails.

2. Checking exists() and then deleting

It looks safe, but the state can change between the check and the delete, so there is a race. Use unlink(missing_ok=True) or try/except FileNotFoundError instead.

3. Using unlink() on a folder, or rmdir() on a full one

unlink() is for files and rmdir() is for empty folders only. Reach for shutil.rmtree() only when you truly need to delete a full folder, and guard it with the checks above.

4. Deleting a file that is still open on Windows

On Windows, unlinking a file that is still open, in your own code or in another program such as Excel, typically raises PermissionError. Open files in a with block and delete them only after the block ends; if another program holds the file, catch the error and retry later.

Best practices

Best practices

  • Confine every deleting function to one root folder and pass that root in as a parameter.
  • Default to dry_run=True so callers must deliberately pass False to delete for real.
  • Log the name of every file you delete, so you can answer when someone asks what disappeared.
  • Always test deleting code inside a temporary directory.

Mini challenge

Mini challenge: clean old exports with a dry run

Write clean_old_files(), which finds .csv files in a folder that are older than max_age_days; with dry_run=True it only returns the list, and with dry_run=False it actually deletes them.

  • dry_run defaults to True, so nothing is deleted by accident
  • Search only the given folder, with folder.glob("*.csv")
  • Work out each file's age from path.stat().st_mtime
  • Test in a temporary directory, setting file times with os.utime()
clean_exports.py
import os
import tempfile
import time
from pathlib import Path

DAY = 24 * 60 * 60


def clean_old_files(folder: Path, max_age_days: int, dry_run: bool = True) -> list[str]:
    """Return the .csv files older than max_age_days; delete them unless dry_run."""
    # TODO: compute the cutoff timestamp from time.time()
    # TODO: loop over sorted(folder.glob("*.csv")), keep regular files older than cutoff
    # TODO: delete each match only when dry_run is False
    ...


with tempfile.TemporaryDirectory() as tmp:
    # TODO: make an exports folder with jan.csv (40 days), feb.csv (10), mar.csv (2)
    # TODO: use os.utime() to back-date each file
    # TODO: print a dry run, the folder content, a real run, and what is left
    ...

Expected: The program prints: Dry run would delete: ['jan.csv'] Still there: ['feb.csv', 'jan.csv', 'mar.csv'] Deleted: ['jan.csv'] Left: ['feb.csv', 'mar.csv']

Show hint

cutoff = time.time() - max_age_days * DAY. A file whose st_mtime is smaller than the cutoff is older. os.utime(path, (stamp, stamp)) sets both the access and the modification time.

Show solution
clean_exports.py
import os
import tempfile
import time
from pathlib import Path

DAY = 24 * 60 * 60


def clean_old_files(folder: Path, max_age_days: int, dry_run: bool = True) -> list[str]:
    """List (and unless dry_run, delete) .csv files older than max_age_days."""
    cutoff = time.time() - max_age_days * DAY
    matched: list[str] = []
    for path in sorted(folder.glob("*.csv")):
        if path.is_file() and path.stat().st_mtime < cutoff:
            matched.append(path.name)
            if not dry_run:
                path.unlink(missing_ok=True)
    return matched


with tempfile.TemporaryDirectory() as tmp:
    exports = Path(tmp) / "exports"
    exports.mkdir()
    now = time.time()
    for name, age_days in [("jan.csv", 40), ("feb.csv", 10), ("mar.csv", 2)]:
        path = exports / name
        path.write_text("id,total\n", encoding="utf-8")
        stamp = now - age_days * DAY
        os.utime(path, (stamp, stamp))         # pretend the file is that old

    print("Dry run would delete:", clean_old_files(exports, 30))
    print("Still there:", sorted(p.name for p in exports.iterdir()))
    print("Deleted:", clean_old_files(exports, 30, dry_run=False))
    print("Left:", sorted(p.name for p in exports.iterdir()))

Quick quiz 1 / 3

What happens when you call Path("exports").rmdir() on a folder that contains one file?

Quick quiz 2 / 3

With root = /srv/exports, what does (root / "../app/settings.py").resolve().is_relative_to(root) return?

Quick quiz 3 / 3

A cleanup script should delete a file if it exists and do nothing otherwise. Which code is best?

What to remember

  • Files deleted from Python skip the Recycle Bin; they are gone for good.
  • Path.unlink() removes a file, Path.rmdir() an empty folder, shutil.rmtree() a whole tree.
  • Prefer unlink(missing_ok=True) or try/except over checking exists() first.
  • Validate paths with resolve() and is_relative_to(root), and give deleting jobs a dry run.

Python Documentation — Reading and Writing Files — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Python Delete Files | Thuta Learning