How to Delete All Files in a Directory in Python

To delete all files in a directory with Python, loop over the folder and remove each file with Path.unlink() (or os.remove()), skipping subfolders. Use shutil.rmtree() only when you want the folder gone too:

from pathlib import Path

for p in Path("temp_reports").iterdir():
    if p.is_file():
        p.unlink()

These deletions are permanent, so every example here works on a throwaway temp_reports folder that’s rebuilt before each run on Python 3.12.5.

I’ll cover os and pathlib, deleting by pattern, including subfolders, a dry run that lists files before deleting, emptying versus removing a folder, and the errors you might hit.

Delete all files in a directory with os

os.listdir() lists everything, so check os.path.isfile() before calling os.remove(); otherwise the subfolder trips it up:

import os

folder = "temp_reports"
for name in os.listdir(folder):
    path = os.path.join(folder, name)
    if os.path.isfile(path):              # skip subfolders like archive\
        os.remove(path)
        print("deleted", name)
print("left:", os.listdir(folder))

Output:

deleted build.tmp
deleted cache.tmp
deleted feb.csv
deleted jan.csv
deleted notes.txt
left: ['archive']
Command Prompt output of Python os.listdir and os.remove deleting every file in a folder while keeping the archive subfolder
Five files deleted; the archive folder stays because it isn’t a file.

Build full paths with os.path.join(); listdir returns names only. See os.path.join() in Python.

Delete all files with pathlib

With pathlib your code gets shorter: iterdir() yields full paths, and unlink() deletes a file:

for path in root.iterdir():
    if path.is_file():
        path.unlink()
print("left:", [p.name for p in root.iterdir()])

Output:

left: ['archive']

Delete files matching a pattern (glob and rglob)

If you only want certain files gone, like temporary files, use glob(). rglob() does the same search through every subfolder:

for path in root.glob("*.tmp"):           # only .tmp files in the top folder
    path.unlink()
print("top level:", sorted(p.name for p in root.iterdir()))

for path in root.rglob("*.tmp"):          # rglob also searches subfolders
    path.unlink()
print("archive:  ", sorted(p.name for p in (root / "archive").iterdir()))

Output:

top level: ['archive', 'feb.csv', 'jan.csv', 'notes.txt']
archive:   ['q3.csv']
Command Prompt output of Python glob deleting .tmp files in a folder and rglob deleting .tmp files in subfolders too
glob("*.tmp") cleaned the top level; rglob also removed old.tmp inside archive.

To see what’s in a folder without deleting anything, see listing files in a directory.

Do a dry run before deleting files

Deleting is permanent; files removed this way don’t go to the Recycle Bin. I always print what would be deleted, check it, then flip the flag:

DRY_RUN = True                            # flip to False when the list looks right

targets = [p for p in root.rglob("*") if p.is_file() and p.suffix in {".tmp", ".csv"}]
for p in targets:
    print(("would delete " if DRY_RUN else "deleting ") + str(p))
    if not DRY_RUN:
        p.unlink()
print(len(targets), "files matched;", "nothing deleted (dry run)" if DRY_RUN else "done")

Output:

would delete temp_reports\build.tmp
would delete temp_reports\cache.tmp
would delete temp_reports\feb.csv
would delete temp_reports\jan.csv
would delete temp_reports\archive\old.tmp
would delete temp_reports\archive\q3.csv
6 files matched; nothing deleted (dry run)
Command Prompt output of a Python dry run listing .tmp and .csv files that would be deleted without deleting them
Six files matched and nothing was deleted. Flip DRY_RUN to False once the list looks right.

Empty a folder vs delete it with shutil.rmtree

shutil.rmtree() deletes a folder and everything inside it. If you need the folder to stay, empty it instead:

import shutil

def empty_folder(folder):
    """Delete everything inside folder but keep the folder itself."""
    for p in folder.iterdir():
        if p.is_dir():
            shutil.rmtree(p)
        else:
            p.unlink()

empty_folder(root)
print("after empty_folder:", list(root.iterdir()), "| folder exists:", root.exists())

shutil.rmtree(root)                        # removes the folder and everything in it
print("after rmtree, folder exists:", root.exists())

Output:

after empty_folder: [] | folder exists: True
after rmtree, folder exists: False
Command Prompt output of a Python function emptying a folder while keeping it, then shutil.rmtree removing the folder entirely
empty_folder left an empty folder; rmtree removed it completely.

To move files somewhere safe instead of deleting them, see how to move a file in Python.

Errors when deleting files in Python

missing_ok=True skips files that are already gone. os.remove() refuses folders, and os.rmdir() only removes empty ones:

import os

missing = root / "does_not_exist.txt"
missing.unlink(missing_ok=True)            # no error if it's already gone
print("missing_ok worked")

try:
    os.remove(root / "archive")            # a folder, not a file
except (PermissionError, IsADirectoryError) as err:
    print(type(err).__name__ + ":", err.strerror)

try:
    os.rmdir(root / "archive")             # rmdir only removes EMPTY folders
except OSError as err:
    print("OSError:", err.strerror)

Output:

missing_ok worked
PermissionError: Access is denied
OSError: The directory is not empty

On Windows, a file that another program has open raises PermissionError. Close it, or catch the error and log it so the rest of the cleanup continues.

Which function deletes what?

FunctionDeletes
os.remove(path) / Path.unlink()One file
os.rmdir(path) / Path.rmdir()One empty folder
shutil.rmtree(path)A folder and everything in it
Loop + unlink()All files in a folder, keeping the folder
glob / rglob + unlink()Files matching a pattern

More file and folder guides:

Frequently asked questions

How do I delete all files in a directory in Python?

Loop over Path(folder).iterdir() and call unlink() on each path where is_file() is True.

How do I delete a folder and everything in it?

Use shutil.rmtree(folder). It’s permanent, so double-check the path first.

How do I delete only certain file types?

Use Path(folder).glob("*.tmp"), or rglob to include subfolders, and unlink each match.

Do deleted files go to the Recycle Bin?

No. os.remove, unlink and rmtree delete permanently. The send2trash package sends files to the Recycle Bin instead.

Why do I get PermissionError when deleting?

The file is open in another program, read-only, or you lack permission. Close it, or catch the error and continue.

Where is shutil.rmtree documented?

See shutil.rmtree in the Python docs.