Question
How can I delete a file or folder in Python?
For example, I want to understand the correct way to remove:
- a single file
- an empty directory
- a directory that contains files or subdirectories
I would also like to know which Python modules and functions are typically used for each case.
Short Answer
By the end of this page, you will understand how Python deletes files and directories, when to use os.remove(), os.rmdir(), shutil.rmtree(), and modern pathlib methods, plus how to avoid common deletion mistakes.
Concept
Deleting something in Python depends on what kind of path you are deleting.
- A file is deleted differently from a directory.
- An empty directory is deleted differently from a non-empty directory.
- Python provides multiple tools for this, mainly from:
osshutilpathlib
The core idea is simple:
- Use file deletion functions for files.
- Use directory deletion functions for folders.
- Use recursive deletion only when you want to remove a folder and everything inside it.
This matters because deleting the wrong path the wrong way causes errors such as:
FileNotFoundErrorIsADirectoryErrorNotADirectoryErrorOSErrorwhen trying to remove a non-empty directory
In real programming, deletion is common when:
- cleaning up temporary files
- removing generated reports
- clearing upload folders
- resetting test environments
- deleting cache directories
Because deletion is destructive, good Python code usually includes checks, clear intent, and error handling.
Mental Model
Think of your filesystem like a house:
- A file is like a single item, such as a book.
- An empty folder is like an empty box.
- A folder with contents is like a box full of smaller boxes and items.
Now imagine three different actions:
os.remove()orPath.unlink()= throw away one itemos.rmdir()orPath.rmdir()= throw away an empty boxshutil.rmtree()= throw away the entire box and everything inside it
If you try to throw away a full box using the "empty box" action, Python stops you. That safety rule prevents accidental data loss.
Syntax and Examples
Core syntax
import os
import shutil
from pathlib import Path
Delete a file
Using os:
import os
os.remove("notes.txt")
Using pathlib:
from pathlib import Path
Path("notes.txt").unlink()
Delete an empty folder
Using os:
import os
os.rmdir("empty_folder")
Using pathlib:
from pathlib import Path
Path("empty_folder").rmdir()
Delete a folder and everything inside it
Step by Step Execution
Example
from pathlib import Path
file_path = Path("report.txt")
if file_path.exists():
file_path.unlink()
print("File deleted")
else:
print("File not found")
Step-by-step
-
from pathlib import Path- Imports the
Pathclass for working with filesystem paths.
- Imports the
-
file_path = Path("report.txt")- Creates a path object pointing to
report.txt. - This does not delete anything yet.
- Creates a path object pointing to
-
if file_path.exists():- Checks whether the file actually exists.
- If it does not exist, the
elseblock will run.
-
file_path.unlink()- Deletes the file.
- If
report.txtis a normal file, it is removed from the filesystem.
Real World Use Cases
Common practical uses
Cleaning up temporary files
Scripts often create temporary CSV, log, or export files that should be removed after processing.
import os
if os.path.exists("temp.csv"):
os.remove("temp.csv")
Resetting a cache directory
Applications may clear a generated cache folder before rebuilding it.
import shutil
shutil.rmtree("cache", ignore_errors=True)
Removing uploaded files
A web app may delete old uploads when a user replaces a profile picture.
Cleaning test data
Automated tests often create files and directories, then delete them during teardown.
Deleting generated build output
Development tools may remove folders like dist/, build/, or temporary artifacts before a new run.
Real Codebase Usage
In real projects, developers usually do more than call a delete function directly.
Common patterns
Guard clauses
Check the path type before deleting.
from pathlib import Path
import shutil
path = Path("data")
if not path.exists():
print("Nothing to delete")
elif path.is_file():
path.unlink()
elif path.is_dir():
shutil.rmtree(path)
Validation before destructive actions
Programs often make sure the target is inside an expected directory to avoid deleting the wrong location.
from pathlib import Path
base = Path("/safe/workspace").resolve()
target = (base / "old_logs").resolve()
if base in target.parents:
print("Target is inside workspace")
Error handling
Deletion can fail because of permissions, file locks, or missing paths.
from pathlib import Path
try:
Path("locked_file.txt").unlink()
FileNotFoundError:
()
PermissionError:
()
Common Mistakes
1. Using os.remove() on a folder
Broken code:
import os
os.remove("my_folder")
Why it fails:
os.remove()is for files, not directories.
Use this instead:
import os
os.rmdir("my_folder")
Or, if the folder is not empty:
import shutil
shutil.rmtree("my_folder")
2. Trying to remove a non-empty directory with os.rmdir()
Broken code:
import os
os.rmdir("project")
Why it fails:
os.rmdir()only removes empty directories.
Fix:
import shutil
shutil.rmtree("project")
Comparisons
Deletion methods in Python
| Task | Recommended tool | Works on files? | Works on empty dirs? | Works on non-empty dirs? |
|---|---|---|---|---|
| Delete one file | os.remove() / Path.unlink() | Yes | No | No |
| Delete one empty directory | os.rmdir() / Path.rmdir() | No | Yes | No |
| Delete directory tree recursively | shutil.rmtree() | No | Yes | Yes |
os vs
Cheat Sheet
# Delete a file
import os
os.remove("file.txt")
from pathlib import Path
Path("file.txt").unlink()
# Delete an empty folder
os.rmdir("empty_folder")
Path("empty_folder").rmdir()
# Delete a folder with contents
import shutil
shutil.rmtree("folder_name")
Rules
os.remove()andPath.unlink()are for filesos.rmdir()andPath.rmdir()are for empty directories onlyshutil.rmtree()is for directories and all contents- Deletion can raise exceptions if the path is missing, locked, or protected
Useful checks
path.exists()
path.is_file()
path.is_dir()
Common exceptions
FileNotFoundError— path does not existPermissionError— not allowed to delete itOSError— often happens when directory is not empty or system-level deletion fails
FAQ
How do I delete a file in Python?
Use os.remove("file.txt") or Path("file.txt").unlink().
How do I delete an empty folder in Python?
Use os.rmdir("folder") or Path("folder").rmdir().
How do I delete a non-empty folder in Python?
Use shutil.rmtree("folder") to remove the folder and everything inside it.
What is the difference between os.remove() and os.rmdir()?
os.remove() deletes files. os.rmdir() deletes empty directories.
Is shutil.rmtree() dangerous?
Yes. It recursively deletes everything inside the target directory, so you should validate the path carefully before using it.
Should I use os or pathlib for deletion?
Both work. pathlib is often easier to read, especially for beginners.
What happens if the file does not exist?
Python usually raises unless you check first or handle the exception.
Mini Project
Description
Build a small cleanup script that deletes a file if it exists and removes a temporary folder if it exists. This demonstrates the difference between deleting a file and deleting a directory tree, which is a very common maintenance task in scripts, automation, and tests.
Goal
Create a Python script that safely removes a target file and a target folder, printing clear messages for each action.
Requirements
- Define one path for a file and one path for a folder
- Check whether each path exists before trying to delete it
- Delete the file with the correct file deletion method
- Delete the folder with the correct directory deletion method
- Print a message describing what happened for each path
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.