Deleting Files and Folders in Python
Deleting Files and Folders
Programs often need to clean up after themselves: removing temporary files, clearing old exports, deleting outdated logs, or removing files a user no longer needs. Python handles file and folder deletion through the built-in os module, which provides functions for interacting with the operating system.
Warning: Files deleted with Python are removed permanently. They do not go to the Recycle Bin or Trash. Always double-check what your code is about to delete.
The os Module
The os module is part of Python's standard library, so it is always available — you only need to import it:
import os
| Function | Purpose |
|---|---|
os.remove(path) | Deletes a file |
os.path.isfile(path) | Returns True if the path is an existing file |
os.path.exists(path) | Returns True if the path exists (file or folder) |
os.rmdir(path) | Deletes an empty folder |
Removing a File
To delete a file, use os.remove() with the file's name or path.
Example: Deleting a File
import os
os.remove("old_data.txt")
If old_data.txt exists in the current working directory, it is deleted. The function produces no output on success.
What Happens If the File Does Not Exist?
import os
os.remove("missing.txt")
Output:
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
The program crashes unless this situation is handled.
Checking Whether a File Exists Before Deleting
To avoid errors, confirm that the file exists before removing it.
Example: Safe File Deletion
import os
file_name = "old_data.txt"
if os.path.isfile(file_name):
os.remove(file_name)
print("File deleted successfully.")
else:
print("File not found.")
Expected output (if the file exists):
File deleted successfully.
Expected output (if it does not):
File not found.
Why os.path.isfile() instead of os.path.exists()? isfile() returns True only for files. exists() also returns True for folders, and calling os.remove() on a folder raises an error. Checking specifically for a file makes the intent clear and the code safer.
Alternative: Handling the Exception
Another common approach is to try the deletion and handle the error if it happens:
import os
try:
os.remove("old_data.txt")
print("File deleted successfully.")
except FileNotFoundError:
print("File not found.")
This version avoids a subtle problem: in programs where other processes might delete the same file, the file could disappear between the check and the deletion. Trying first and handling the error covers that case.
| Approach | Advantages |
|---|---|
Check first with os.path.isfile() | Easy to read; clearly separates the two outcomes |
Try and handle FileNotFoundError | Also safe when other programs might delete the file at the same time |
Other errors are possible too — for example, PermissionError if the file is read-only, or (on Windows) if another program has the file open.
Deleting a Folder
To remove a folder (directory), use os.rmdir(). It only works on empty folders.
Example: Removing an Empty Folder
import os
os.rmdir("temp_folder")
If temp_folder exists and is empty, it is deleted.
What If the Folder Is Not Empty?
import os
os.rmdir("reports")
Output (when reports contains files):
OSError: [Errno 39] Directory not empty: 'reports'
The exact error number and wording vary between operating systems. This restriction is a safety feature: os.rmdir() will never remove files you did not explicitly delete.
Emptying a Folder First
To delete a folder that contains files, delete the files first, then the folder:
import os
folder = "temp_folder"
for name in os.listdir(folder):
path = os.path.join(folder, name)
if os.path.isfile(path):
os.remove(path)
os.rmdir(folder)
print("Folder removed.")
Expected output:
Folder removed.
os.listdir(folder)returns the names of everything inside the folder.os.path.join(folder, name)builds the full path correctly for the current operating system.- After all the files are removed,
os.rmdir()can delete the now-empty folder.
This example assumes the folder contains only files. For folders that contain subfolders, Python's shutil.rmtree(folder) deletes the folder and everything inside it — use it with great care, because the entire contents are removed permanently.
The Modern Alternative: pathlib
Python's standard library also includes the pathlib module, which represents paths as objects. Many developers prefer it for new code:
from pathlib import Path
file_path = Path("old_data.txt")
if file_path.is_file():
file_path.unlink()
print("File deleted successfully.")
| Task | os Module | pathlib |
|---|---|---|
| Delete a file | os.remove(path) | Path(path).unlink() |
| Check for a file | os.path.isfile(path) | Path(path).is_file() |
| Delete an empty folder | os.rmdir(path) | Path(path).rmdir() |
Since Python 3.8, Path.unlink(missing_ok=True) deletes a file and does nothing if it is already missing, without raising an error.
Practical Example: Cleaning Up Old Temporary Files
import os
for name in os.listdir("."):
if name.endswith(".tmp") and os.path.isfile(name):
os.remove(name)
print("Deleted:", name)
Example output:
Deleted: cache_01.tmp
Deleted: upload_part.tmp
The loop checks every item in the current directory (".") and deletes only files ending in .tmp. Filtering carefully by name and type is essential in any code that deletes files automatically.
Best Practices for Deleting Files
- Check before deleting, or handle
FileNotFoundError. - Be specific — filter by exact name, extension, or folder, and never delete based on a broad pattern without reviewing it.
- Test with print statements first — print the paths your code would delete before enabling the actual deletion.
- Close files before deleting them — on Windows, an open file cannot be deleted.
- Prefer
os.rmdir()overshutil.rmtree()unless you truly need to delete a folder's entire contents.
Common Mistakes
| Mistake | Problem |
|---|---|
| Deleting a file that does not exist | FileNotFoundError |
Using os.remove() on a folder | An error — use os.rmdir() for folders |
Using os.rmdir() on a folder with files | OSError: Directory not empty |
| Deleting a file that is still open (Windows) | PermissionError |
| Using the wrong working directory | The wrong file is deleted, or the file is not found |
Using shutil.rmtree() carelessly | Permanently deletes everything inside the folder |
Related Concepts
- Python File Handling — opening files and file modes
- Python Writing and Creating Files — creating the files you may later delete
- Python Modules — importing
os,shutil, andpathlib - Python Exception Handling — handling
FileNotFoundErrorandPermissionError