os.remove() method in Python
os.remove() function in Python is used to delete files from the file system. It is part of the os module, which provides tools for interacting with the operating system. This method is useful when you need to programmatically remove files during automation, cleanup tasks, or file management operations.
Note: It cannot delete directories. If the path points to a directory, a IsADirectoryError will be raised.
Syntax
os.remove(path, *, dir_fd=None)
Parameters:
- path (Required): A path-like object (string or bytes) representing the file to remove.
- dir_fd (Optional): Refers to a directory file descriptor. Ignored if an absolute path is provided.
- * before dir_fd means it must be specified as a keyword argument.
Return Type: This method does not return any value.
Examples of os.remove Method:
Example 1: Remove a File
This example shows how to remove a specific file by constructing its path and using os.remove().
import os
# File path
file = 'file.txt'
location = '/home/User/Documents'
path = os.path.join(location, file)
os.remove(path)
print(f"{file} has been removed successfully")
Output
file.txt has been removed successfully
Explanation: The code constructs the full path to file.txt and deletes it using os.remove().
Example 2: Attempting to Remove a Directory
This example demonstrates what happens when we try to remove a directory using os.remove(), which is not allowed:
import os
# Path to a directory
path = '/home/User/Documents/myfolder'
os.remove(path)
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 6, in <module>
os.remove(path)
~~~~~~~~~^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: '/home/User/Documents/myfolder'
Explanation: Since path points to a directory, os.remove() raises a IsADirectoryError.
Example 3: Handling Errors
This example shows how to handle errors, using a try-except block when attempting to remove a path.
import os
path = '/home/User/Documents/myfolder'
try:
os.remove(path)
print(f"{path} removed successfully")
except OSError as e:
print(e)
print("File path cannot be removed")
Output
[Errno 21] Is a directory: '/home/User/Documents/ihritik' File path can not be removed
Explanation: The code uses try-except to handle errors like missing files, invalid paths, or attempts to delete a directory.
Related articles: