In this Python tutorial, you will learn how to delete a file with os.remove(), check whether a path refers to a file, handle common deletion errors, and use pathlib.Path.unlink() as an alternative.
Delete a File with Python os.remove()
To delete a file in Python, import the os module and pass the file path to os.remove(). The function removes a file or symbolic link. It does not remove a directory.
Use a relative path when the file is inside the program’s working directory, or use an absolute path when the file is elsewhere. File deletion is normally permanent, so confirm the path before running the program.
os.remove() Syntax for File Deletion
The syntax of os.remove() function is:
os.remove(file_path)
The file_path argument can be a string, bytes value, or path-like object that identifies the file to delete. os.unlink() is an alias with the same behavior.
If the file does not exist, os.remove() raises FileNotFoundError. It may also raise PermissionError when the process does not have permission to delete the file, or IsADirectoryError when the path points to a directory.
Python File Deletion Examples
1. Delete an Existing File with os.remove()
In the following Python program, we are deleting a file present at the location D:/data.txt. The success message is printed only when os.remove() completes without raising an exception.
Python Program
import os
#delete the file
os.remove("D:/data.txt")
print('The file is deleted.')
Output
The file is deleted.
If D:/data.txt is missing, the program stops at os.remove() with a FileNotFoundError. Use a file check or exception handling when a missing file is an expected condition.
2. Check Whether the File Exists Before Deleting It
You can check whether the path refers to an existing regular file before attempting deletion. This approach is easy to read, but the file could still be removed by another process between the check and the call to os.remove().
os.path.isfile() returns True when the path exists and refers to a regular file. It returns False for a missing path or a directory.
Python Program
import os
file_path = "D:/data.txt"
#check if file is present
if(os.path.isfile(file_path)):
#delete the file
os.remove(file_path)
print('The file is deleted.')
else:
print('The file is not present.')
If the file is present and deleted, you would get the following output.
Output
The file is deleted.
If the file is not present, the program prints the following message.
Output
The file is not present.
3. Delete a File Safely with try and except
Exception handling is usually the safer pattern because it performs the deletion directly and handles the result. It also lets you distinguish a missing file from a permission problem or a directory path.
import os
file_path = "D:/data.txt"
try:
os.remove(file_path)
print("The file is deleted.")
except FileNotFoundError:
print("The file does not exist.")
except PermissionError:
print("Permission denied. The file was not deleted.")
except IsADirectoryError:
print("The path points to a directory, not a file.")
This pattern is useful in scripts that may run repeatedly, cleanup jobs, and applications where another process could change the file system at the same time.
4. Delete a File with pathlib.Path.unlink()
The pathlib module provides an object-oriented way to work with file paths. Call Path.unlink() to remove a file or symbolic link.
from pathlib import Path
file_path = Path("D:/data.txt")
try:
file_path.unlink()
print("The file is deleted.")
except FileNotFoundError:
print("The file does not exist.")
When a missing file should be ignored, use missing_ok=True:
from pathlib import Path
Path("D:/data.txt").unlink(missing_ok=True)
With missing_ok=True, no exception is raised when the specified file does not exist. Other errors, such as permission failures, are still raised.
Delete Files by Extension from a Folder
To remove multiple files, iterate over matching paths and delete each file. The following example deletes every .tmp file directly inside a folder. It does not search subfolders.
from pathlib import Path
folder = Path("D:/downloads")
for file_path in folder.glob("*.tmp"):
if file_path.is_file():
file_path.unlink()
print(f"Deleted: {file_path.name}")
Review the folder and file pattern carefully before running bulk deletion code. A broad pattern such as * can match more files than intended.
Delete a File Using a Relative Path
A relative path is resolved from Python’s current working directory, not necessarily from the folder containing the script. You can inspect the current working directory with os.getcwd().
import os
print(os.getcwd())
os.remove("data.txt")
In this example, Python attempts to delete data.txt from the directory returned by os.getcwd().
Delete a File Located Beside the Python Script
When the file is stored beside the Python script, construct its path from __file__ instead of relying on the current working directory.
from pathlib import Path
script_folder = Path(__file__).resolve().parent
file_path = script_folder / "data.txt"
file_path.unlink()
This approach continues to identify the same file even when the script is started from another directory.
Why Python Cannot Delete the File
- The path is incorrect: A relative path is resolved from the current working directory, which may differ from the script’s directory.
- The file does not exist:
os.remove()raisesFileNotFoundError. - The path is a directory: Use
os.rmdir()for an empty directory orshutil.rmtree()for a directory tree. - Permission is denied: The program may lack permission to delete the file, or another process may have locked it.
- The Windows path contains backslashes: Use a raw string such as
r"C:\data\file.txt", escaped backslashes, forward slashes, or aPathobject. - The file is read-only or protected: File attributes and directory permissions can prevent deletion even when the path is correct.
os.remove(), os.rmdir(), and shutil.rmtree()
| Function | Use | Important behavior |
|---|---|---|
os.remove() | Delete one file or symbolic link | Raises an exception when the path is missing or points to a directory |
os.rmdir() | Delete one empty directory | Fails when the directory contains files or subdirectories |
shutil.rmtree() | Delete a directory tree | Removes the directory and everything inside it |
Do not replace os.remove() with shutil.rmtree() unless you deliberately intend to remove an entire directory and its contents.
Python File Deletion FAQs
Does os.remove() raise an error when the file is missing?
Yes. It raises FileNotFoundError. Catch that exception when a missing file is acceptable, or use Path.unlink(missing_ok=True).
What is the difference between os.remove() and os.unlink()?
There is no practical difference for deleting files. In Python, os.remove() and os.unlink() provide the same file-removal behavior.
Can os.remove() delete a directory?
No. Use os.rmdir() for an empty directory. Use shutil.rmtree() only when you intentionally need to delete a directory and all of its contents.
How do I delete a file only when it exists?
You can check with os.path.isfile(), catch FileNotFoundError, or call Path.unlink(missing_ok=True). Exception handling avoids a separate check that can become outdated before deletion occurs.
Python File Deletion Review Checklist
- Confirm that the path identifies the intended file and not a directory.
- Use exception handling when a missing file or permission failure is possible.
- Verify wildcard patterns before deleting multiple files.
- Use
pathlib.Pathwhen path construction and cross-platform readability matter. - Avoid printing a success message before the deletion call completes.
- Use
shutil.rmtree()only when deleting an entire directory tree is intentional.
Summary of Deleting Files in Python
In this Python Tutorial, we learned how to delete a file with os.remove(), check a path with os.path.isfile(), handle deletion errors, remove files with Path.unlink(), and delete matching files from a folder.
TutorialKart.com