🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeHow to Delete Folder Contents in Python

Keeping a directory in place while removing its contents takes a clear choice about whether nested folders count. Python lets you inspect a directory and remove its files, empty child directories, or child trees while leaving the target directory in place.
I’ll walk through choosing the deletion scope and checking what remains, including the output from the complete example.
TL;DR
Use Path.iterdir() to inspect immediate children, unlink files, and remove directories with the method that matches your scope. Keep the target path separate from the children so the parent folder remains in place.
- Files: Path.unlink() or os.remove().
- Empty directories: Path.rmdir() or os.rmdir().
- Non-empty child trees: shutil.rmtree(), only when recursive deletion is intended.
What Is Deleting Folder Contents in Python?
From the reader’s perspective, clearing a folder means deleting selected entries inside it while keeping its directory. The intended scope may include direct files, empty child directories, or complete child trees.
A directory contains entries called children, including files, subdirectories, and symbolic links. A symbolic link points to another path. Path.iterdir() lists only the immediate entries, so inspect nested directories separately when they are in scope.
Path.unlink() removes a file or symbolic link.
Path.rmdir() removes an empty directory. The AskPython shutil guide covers high-level file operations. For a single file, see deleting files in Python.
The examples use a temporary demo directory beside the script, then remove that test data.
Choose the scope before choosing the operation: direct files, empty child folders, or every descendant lead to different loops.
Recursive removal suits disposable build output or a generated cache when the target is known.
Python provides three useful filesystem interfaces. pathlib represents paths as objects, os supplies file and directory functions, and shutil handles higher-level operations such as recursive removal. I use pathlib here because each child remains a Path object throughout the examples.
The word “contents” can mean different scopes. A direct-child pass sees files and folders one level down, while a recursive pass also reaches grandchildren. Decide which meaning you intend before writing the loop because recursive removal can delete data that the direct-child version leaves alone.
Deleting an entry also differs from emptying a directory object. Filesystem APIs take paths, and the method you call determines whether a file, empty directory, or directory tree is accepted. A loop should therefore branch on each child instead of applying one removal call to every name.
Use a dry-run list when the target comes from configuration or user input. Printing candidates first lets you catch a wrong base path before any unlink or recursive operation runs. Once the selection is correct, keep that same selection rule in the deletion pass.
How to Delete Folder Contents in Python Step by Step
Process each immediate entry according to the chosen scope. I ran the examples from delete_contents_demo.py in this workspace. The output below is from that execution.
Step 1: Choose the directory and inspect its children
Use a Path object for the target and iterate over its direct entries. A relative path is resolved from the process’s current working directory, so an absolute path or a path based on a known script location reduces ambiguity.
from pathlib import Path
folder = Path("/path/to/folder")
for child in folder.iterdir():
print(child.name, "directory" if child.is_dir() else "file")
Replace the example path with the directory you intend to clean. Review the names first when the target can contain valuable data. The deletion loop has no undo.
Step 2: Remove files and empty child directories only
Unlink files and remove only empty child directories when nested data must be retained. A non-empty child causes rmdir() to raise an error. Skip it deliberately or handle that error without masking permission failures.
from pathlib import Path
folder = Path("/path/to/folder")
for child in folder.iterdir():
if child.is_symlink() or child.is_file():
child.unlink()
elif child.is_dir():
try:
child.rmdir()
except OSError:
pass # leave non-empty or inaccessible directories for review
The symlink check comes first so a link to a directory is treated as a link entry instead of a directory tree. This version preserves non-empty children, but its broad OSError catch also skips errors other than “directory not empty”. Production code should catch the expected exception narrowly and report the path.
Step 3: Recursively clear descendants but keep the target
Use shutil.rmtree() on each actual child directory when all nested content should be removed, and use unlink() for file and link entries.
import shutil
from pathlib import Path
folder = Path("/path/to/folder")
for child in folder.iterdir():
if child.is_symlink() or child.is_file():
child.unlink()
elif child.is_dir():
shutil.rmtree(child)
Because the argument is child, the containing folder is not passed to the recursive remover.
Step 4: Delete only files with a chosen suffix
Filter direct children by suffix when only one file type should be removed. This leaves subdirectories untouched and does not search nested levels.
from pathlib import Path
folder = Path("/path/to/folder")
for child in folder.iterdir():
if child.is_file() and child.suffix.lower() == ".txt":
child.unlink()
suffix.lower() makes this extension comparison case-insensitive, so REPORT.TXT matches too. For nested matching files, use an explicit recursive traversal and verify each candidate before deleting it.
For a production filter, make the directory and extension explicit inputs rather than embedding them in a reusable function. Return or log the selected paths so a caller can review what the rule matched. If the matching rule is wrong, correcting it before deletion is safer than trying to recover afterward.
Hidden files are still directory entries and can match a suffix test. A name such as .env has no ordinary suffix in pathlib, while archive.tar.gz has .gz as its final suffix. Test representative names from the directory before running a cleanup against important data.
Step 5: Run the complete example and check its result
The demonstration creates disposable fixtures, exercises all three scopes, prints the remaining entries and removes its fixture directory. To reproduce it, run python3 delete_contents_demo.py from the directory containing the source file.
Direct clear: ['nested-child']
Non-empty child kept: True
Recursive clear: []
Parent kept: True
After .txt filter: ['photo.png']

The first result retains the non-empty nested directory, the second leaves the recursive target empty, and the suffix filter keeps the image file. The screenshot shows this same executed command and its complete output.
What Can Go Wrong When Clearing a Folder?
Choose the failure policy before deleting anything. A loop can stop on the first error, skip a known case, or collect failures and continue, but each choice affects how much data is removed.
What happens when a directory is not empty?
Path.rmdir() raises OSError when a child directory still contains entries. That behavior is useful when preserving nested content matters: leave the child in place and continue with the next sibling. Avoid catching every OSError and treating it as “not empty,” because permission errors and storage failures need a different response.
Python reports a non-empty directory through OSError, and the subclass can vary by platform. Check errno if your code must separate that case from permission or storage errors.
How should the loop report a failed operation?
Catch OSError close to unlink() or rmdir() so the message identifies the entry that failed. Continuing after an error is reasonable for a batch cleanup, but the caller should receive a failure list and a non-success status.
failed = []
for child in folder.iterdir():
try:
child.unlink()
except IsADirectoryError:
continue # handle directories in a separate branch
except OSError as error:
failed.append((child, error))
for path, error in failed:
print(f"Could not remove {path}: {error}")
This fragment is for a file-only pass. It skips directories for a later decision and preserves each error for reporting rather than declaring the whole cleanup successful.
What if another process changes the folder?
A directory listing gives names without locking entries. Another process may alter one before your loop reaches it. Treat FileNotFoundError as a possible race only when that matches the task, and log it when the caller needs an audit trail.
For a high-impact cleanup, stop writers first or work on a dedicated directory that the application owns. Rechecking a path does not reserve it against concurrent changes.
How do I avoid deleting the wrong directory?
Build the target from a known base directory, resolve it, then compare it with the allowed parent before recursive removal. Do not accept an empty string or a path assembled from untrusted input without validation. A mistaken parent path can turn a child cleanup into a much larger deletion.
from pathlib import Path
base = Path("/srv/app/cache").resolve()
target = (base / "job-123").resolve()
if target == base or base not in target.parents:
raise ValueError(f"Refusing unexpected target: {target}")
This containment check is a guardrail for an ordinary trusted filesystem. If an attacker can alter directories concurrently, path-based checks alone do not provide a race-free security boundary.
Does a suffix filter search nested folders?
The step 4 loop examines immediate children only. To visit nested entries, use Path.rglob() deliberately. Decide whether files reached through symlinked directories belong in scope before traversing.
Before running a destructive filter, print the candidate paths and inspect a sample. A suffix can be misleading when a file has multiple dots, and a backup named report.txt.bak does not have .txt as its final suffix.
Should I use pathlib, os, or shutil?
Pathlib fits code that already uses Path objects. os.scandir() provides directory entries with metadata, while shutil.rmtree() removes a chosen child tree.
For valuable files, make a backup and run a listing-only pass first. The AskPython os module reference explains related operating-system functions.
Conclusion
Set the target explicitly, decide whether nested data is in scope, and apply the matching operation to each child. Review the path before a recursive deletion.
For related operations, read the Python pathlib documentation and Python shutil documentation.
FAQ
These answers clarify common differences between clearing a directory and removing it.
How do I delete files but keep the folder in Python?
Iterate over the folder’s children, unlink files, and remove child directories only if they are empty or recursive removal is intended. Do not pass the parent folder itself to shutil.rmtree().
Can os.remove() delete a directory?
No. os.remove() removes a file path. Use os.rmdir() for an empty directory or shutil.rmtree() for a directory tree you intend to delete.
Does Path.iterdir() include files in subfolders?
No. Path.iterdir() returns only the target directory’s immediate children. Traverse child directories separately when nested files are in scope.


