Delete Files and Directories in Python: os, pathlib, and shutil

Python provides several built-in modules for deleting files and directories. This article explains how to use os.remove(), pathlib.Path.unlink(), and shutil.rmtree() to remove files and directories, including pattern-based deletion and recursive directory removal.
Deleting Files
In Python you can use os.remove(), os.unlink(), pathlib.Path.unlink() to delete a single file.
The os
module provides a portable way of interacting with the operating system.
To delete a single file with os.remove(), pass the path to the file as an argument:
import os
file_path = '/tmp/file.txt'
os.remove(file_path)os.remove() and os.unlink() functions are semantically identical:
import os
file_path = '/tmp/file.txt'
os.unlink(file_path)If the specified file does not exist
, a FileNotFoundError error is thrown. Both os.remove() and os.unlink() can delete only files, not directories. If the given path points to a directory, they will throw an IsADirectoryError error.
Deleting a file requires write and execute permission on the directory containing the file. Otherwise, you will get a PermissionError.
To avoid errors when deleting files, you can use exception handling to catch the exception and send a proper error message:
import os
file_path = '/tmp/file.txt'
try:
os.remove(file_path)
except OSError as e:
print("Error: %s : %s" % (file_path, e.strerror))The pathlib
module provides an object-oriented interface for working with filesystem paths. It is available in Python 3.4 and above.
To delete a file with the pathlib module, create a Path object pointing to the file and call the unlink() method on the object:
from pathlib import Path
file_path = Path('/tmp/file.txt')
try:
file_path.unlink()
except OSError as e:
print("Error: %s : %s" % (file_path, e.strerror))In Python 3.8 and above, you can pass missing_ok=True to suppress the FileNotFoundError if the file does not exist:
from pathlib import Path
Path('/tmp/file.txt').unlink(missing_ok=True)pathlib.Path.unlink(), os.remove(), and os.unlink() can also be used to delete a symlink
.
Delete Files by Pattern
You can use the glob
module to match multiple files based on a pattern. For example, to remove all .txt files in the /tmp directory, you would use something like this:
import os
import glob
files = glob.glob('/tmp/*.txt')
for f in files:
try:
os.remove(f)
except OSError as e:
print("Error: %s : %s" % (f, e.strerror))To recursively delete all .txt files in the /tmp directory and all subdirectories under it, pass the recursive=True argument to the glob() function and use the ** pattern:
import os
import glob
files = glob.glob('/tmp/**/*.txt', recursive=True)
for f in files:
try:
os.remove(f)
except OSError as e:
print("Error: %s : %s" % (f, e.strerror))The pathlib module includes two glob functions, glob() and rglob() to match files in a given directory. glob() matches files only in the top level directory. rglob() matches all files in the directory and all subdirectories, recursively. The following example code deletes all .txt files in the /tmp directory:
from pathlib import Path
for f in Path('/tmp').glob('*.txt'):
try:
f.unlink()
except OSError as e:
print("Error: %s : %s" % (f, e.strerror))Deleting Directories (Folders)
In Python you can use os.rmdir() and pathlib.Path.rmdir() to delete an empty directory and shutil.rmtree() to delete a non-empty directory.
The following example shows how to remove an empty directory:
import os
dir_path = '/tmp/img'
try:
os.rmdir(dir_path)
except OSError as e:
print("Error: %s : %s" % (dir_path, e.strerror))Alternatively, you can delete directories with the pathlib module:
from pathlib import Path
dir_path = Path('/tmp/img')
try:
dir_path.rmdir()
except OSError as e:
print("Error: %s : %s" % (dir_path, e.strerror))The shutil
module allows you to perform a number of high-level operations on files and directories.
With the shutil.rmtree() function you can delete a given directory including its content:
Be careful with shutil.rmtree() because it removes the directory and everything under it recursively.
import shutil
dir_path = '/tmp/img'
try:
shutil.rmtree(dir_path)
except OSError as e:
print("Error: %s : %s" % (dir_path, e.strerror))The argument passed to shutil.rmtree() cannot be a symbolic link to a directory.
To silently ignore any errors during deletion, pass ignore_errors=True:
import shutil
shutil.rmtree('/tmp/img', ignore_errors=True)Quick Reference
For a printable quick reference, see the Python cheatsheet .
| Task | Function |
|---|---|
| Delete a file | os.remove(path) or Path(path).unlink() |
| Delete a file (no error if missing) | Path(path).unlink(missing_ok=True) |
| Delete a symlink | os.remove(path) or Path(path).unlink() |
| Delete an empty directory | os.rmdir(path) or Path(path).rmdir() |
| Delete a directory and its contents | shutil.rmtree(path) |
| Delete a directory, ignore errors | shutil.rmtree(path, ignore_errors=True) |
| Delete files by pattern | glob.glob(pattern) + os.remove() |
| Delete files recursively by pattern | glob.glob('**/*.ext', recursive=True) + os.remove() |
| Delete files with pathlib glob | Path(dir).glob('*.ext') + .unlink() |
FAQ
What is the difference between os.remove() and os.unlink()?
They are identical: os.unlink() is simply an alias for os.remove(). Both delete a single file and raise FileNotFoundError if the path does not exist.
How do I delete a file only if it exists?
Use pathlib.Path.unlink(missing_ok=True) (Python 3.8+) to suppress the error if the file is missing. Alternatively, wrap os.remove() in a try/except block catching FileNotFoundError.
How do I delete a directory and all its contents?
Use shutil.rmtree(path). To suppress errors, pass ignore_errors=True. Note that os.rmdir() only works on empty directories.
Can I use pathlib to delete files matching a pattern?
Yes. Use Path(directory).glob('*.txt') to match files and call .unlink() on each result. For recursive matches, use .rglob('*.txt') instead.
Conclusion
Python provides several built-in modules for deleting files and directories. Use os.remove() or pathlib.Path.unlink() for single files, os.rmdir() or pathlib.Path.rmdir() for empty directories, and shutil.rmtree() to recursively delete a directory and all of its contents. Be extra careful when removing files or directories, as deleted files cannot be easily recovered.
Tags
Linuxize Weekly Newsletter
A quick weekly roundup of new tutorials, news, and tips.
About the authors

Dejan Panovski
Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.
View author page