To recursively delete all files and subfolders in a directory (but
not the root directory itself), you can use built-in APIs depending on your programming language. Here's how to do it in
C#, Java, Python, and
Bash:
In C#
using System.IO;
public static void ClearDirectory(string path)
{
if (!Directory.Exists(path))
return;
// Delete all files
foreach (string file in Directory.GetFiles(path))
{
File.SetAttributes(file, FileAttributes.Normal); // in case of read-only
File.Delete(file);
}
// Delete all subdirectories recursively
foreach (string dir in Directory.GetDirectories(path))
{
Directory.Delete(dir, true); // true = recursive delete
}
}
Keeps the root directory (path) intact.
Handles nested folders and files.
Use FileAttributes.Normal in case files are marked read-only.
In Java
import java.io.File;
public static void clearDirectory(File dir) {
if (dir.exists() && dir.isDirectory()) {
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
clearDirectory(file);
file.delete();
} else {
file.delete();
}
}
}
}
Call with: clearDirectory(new File("your/path")).
In Python
import os
import shutil
def clear_directory(path):
if not os.path.isdir(path):
return
for filename in os.listdir(path):
file_path = os.path.join(path, filename)
if os.path.isdir(file_path):
shutil.rmtree(file_path)
else:
os.remove(file_path)
Preserves the root directory.
Use shutil.rmtree() for recursive folder deletion.
In Bash (Linux/macOS)
rm -rf /your/directory/path/*
Deletes all contents inside the folder, but not the folder itself.
Be cautious — use echo to test paths before running rm -rf.
Tips
Always validate the path to avoid deleting unintended data.
Use logging or user confirmation for destructive operations.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To recursively delete all files and subfolders in a directory (but not the root directory itself), you can use built-in APIs depending on your programming language. Here's how to do it in C#, Java, Python, and Bash:
In C#
path) intact.FileAttributes.Normalin case files are marked read-only.In Java
Call with:
clearDirectory(new File("your/path")).In Python
shutil.rmtree()for recursive folder deletion.In Bash (Linux/macOS)
echoto test paths before runningrm -rf.Tips