![]() |
VOOZH | about |
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.
Example:
Output
File deleted successfully
Syntax
os.remove(path, *, dir_fd=None)
Parameters:
Return Type: This method does not return any value.
This example shows how to remove a specific file by constructing its path and using os.remove().
file.txt has been removed successfully
Explanation: The code constructs the full path to file.txt and deletes it using os.remove().
This example demonstrates what happens when we try to remove a directory using os.remove(), which is not allowed:
Output:
Traceback (most recent call last):
...
IsADirectoryError: [Errno 21] Is a directory: '/home/User/Documents/myfolder'
Explanation: Since path points to a directory, os.remove() raises a IsADirectoryError.
This example shows how to handle errors, using a try-except block when attempting to remove a path.
[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.
Files with a specific extension can be identified and deleted automatically using os.remove(). This is useful for cleanup tasks, such as removing temporary, log, or backup files from a directory.
Output
1. If the directory contains the files:
Deleted: app.log
Deleted: error.log
Deleted: debug.log
2. If no .log files are present, the program will produce no output.
Explanation:
Before deleting a file, it's better to verify that the file exists. This helps prevent errors and ensures that the deletion operation is performed only on valid file paths.
File does not exist
Explanation:
Note: Files deleted using os.remove() are permanently removed and cannot be recovered through the Recycle Bin or Trash.