As a Python developer, you‘ll often need to interact with the file system to delete files and folders. However, trying to delete non-existent files will raise errors and crash your program. To avoid this, you first need to check if the file exists before attempting to delete it.
In this comprehensive guide, we‘ll explore several methods in Python for safely deleting files if they exist.
Overview
Here‘s what we‘ll cover:
- Checking if a file exists with
os.path.exists() - Using
try/exceptblocks to catch file not found errors - Deleting files with
os.remove()andos.unlink() - Comparing remove vs unlink for deleting files
- Handling permissions errors while deleting files
- Best practices for robust file deletion code
- Deleting files matched by patterns and in directories
- Removing empty folders after deleting files
By the end, you‘ll have strong knowledge of robust techniques for deleting files in Python.
Checking If a File Exists
Before deleting a file, you‘ll want to check if it actually exists to avoid errors. Python‘s os.path module provides an easy way to check for file existence.
Here‘s an example:
import os
file_path = "/path/to/file.txt"
if os.path.exists(file_path):
# file exists
else:
# file doesn‘t exist
The os.path.exists() method returns True if the file at the given path exists, and False otherwise.
This gives us a way to check for a file‘s existence before trying to delete it.
Catching Errors with try/except
Another way to robustly handle missing files is to wrap our delete code in a try/except block:
import os
try:
os.remove("some_missing_file.txt")
except FileNotFoundError:
print("File was not found, moving on...")
This catches the error gracefully if the file is missing, rather than crashing our program.
Deleting Files with os.remove()
Now let‘s explore methods for actually deleting files in Python.
The os module provides a function called os.remove() to delete a file by its path:
import os
file_path = "/path/to/file.txt"
os.remove(file_path) # Deletes the file
If the file does not exist, remove() will raise a FileNotFoundError.
So be sure to check that the file exists first with os.path.exists() or use try/except handling.
Comparing os.remove() vs os.unlink()
Python also provides an os.unlink() method with similar behavior to remove():
os.unlink("/path/to/some_file")
The key difference between remove() and unlink() is how they handle deleting read-only files on Windows.
remove() is unable to delete read-only files on Windows, while unlink() will delete them.
So on Windows, prefer using unlink() if you need to forcibly delete read-only files.
Handling Permission Errors While Deleting Files
Another issue that can occur while deleting files is a PermissionError when you don‘t have access to delete the file.
We can refine our try/except block to also handle permission issues:
import os
try:
os.remove("some_file.txt")
except (FileNotFoundError, PermissionError):
print("Unable to delete file due to file not found or permission issue")
Now the code will gracefully handle both missing file and access permission errors.
Best Practices for Deleting Files
Here are some best practices when deleting files in Python:
- Always check that the file exists before trying to delete it
- Wrap delete code in try/except blocks to handle errors
- Specify the exact full path to files rather than relying on the current working directory
- Use
os.path.exists()overos.path.isfile()to check existence –exists()also returns True for symlinks whileisfile()does not - Consider moving files to trash/recycle bin rather than permanent deletion if available
- Handle both missing file and permission errors
- Use
unlink()overremove()on Windows if you need to delete read-only files
These tips will help avoid crashes and ensure expected behavior when deleting files.
Matching and Deleting Files by Patterns
Beyond just deleting a single file by explicit name, you can also match multiple files by patterns and delete them.
The glob module provides an easy way to get files matching a pattern.
Here‘s an example to find and delete .temp files:
import glob
import os
for temp_file in glob.glob("*.temp"):
os.remove(temp_file)
This will delete all files ending with .temp in the current working directory.
You can match complex patterns and delete sets of files without having to specify each one individually.
Deleting Files in Directories
Another case is deleting all files inside a specific directory.
You can get all files in a folder with os.listdir(), then iterate and delete them:
import os
folder = "/path/to/folder"
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
os.remove(file_path)
except OSError:
print(f"Failed to delete {file_path}")
This safely tries deleting all files inside the given folder path.
Removing Empty Folders
After deleting files inside folders, you may want to tidy up and prune any newly empty folders.
We can check if a folder is empty before removing it with os.rmdir():
import os
folder = "/path/to/folder"
if not os.listdir(folder):
os.rmdir(folder) # Remove empty folder
Be careful running rmdir() directly on a folder without checking – it will raise an error if the folder contains any files or subfolders still.
So combine it with os.listdir() to first verify it‘s empty.
Summary
We‘ve covered many approaches to reliably delete files in Python code including:
- Checking file existence with
os.path.exists() - Gracefully handling errors with
try/except - Deleting files by path using
os.remove()andos.unlink() - Following best practices like permissions handling
- Matching and deleting files by patterns like
*.temp - Removing files inside directories
- Deleting empty folders safely
Robust file deletion is important to writing production-quality Python code that interacts with the file system.
Use these techniques to avoid crashes and ensure expected behavior when deleting files from your Python applications.


