How to Delete files in Python using send2trash module? (original) (raw)
Last Updated : 1 Jun, 2026
The send2trash module allows files and folders to be moved to the system's Trash or Recycle Bin instead of being permanently deleted. This provides a safer alternative to functions such as os.remove() and os.rmdir(), as deleted items can be restored if removed accidentally.
- Works across Windows, macOS, and Linux.
- Supports deleting both files and directories.
Installing send2trash
Install send2trash using following command:
pip install send2trash
Delete a File
The send2trash() function moves a file to the system's Trash or Recycle Bin instead of permanently deleting it.
**Example:
Python `
import send2trash
send2trash.send2trash("sample.txt") print("File moved to Trash.")
`
**Output
File moved to Trash.
**Explanation:
- sample.txt is moved to the Trash.
- The file can be restored later if needed.
- No permanent deletion occurs.
**Syntax:
send2trash.send2trash(path)
Delete a Folder
The send2trash() function supports deleting directories by moving them to the Trash or Recycle Bin. Any files and nested folders inside the directory are moved along with it, providing a safe alternative to permanent deletion.
**Example:
Python `
import send2trash
send2trash.send2trash("Documents") print("Folder moved to Trash.")
`
**Output
Folder moved to Trash.
**Explanation:
- send2trash.send2trash() function moves the "Documents" folder to the system's Trash or Recycle Bin.
- Any files and subfolders contained within the folder are also moved to the Trash, allowing them to be restored later if needed.
**Syntax:
send2trash.send2trash(folder_path)
Delete Multiple Files
A list of file paths can be processed to move multiple files to the Trash at once.
**Example:
Python `
import send2trash
files = [ "file1.txt", "file2.txt", "file3.txt" ]
for file in files: send2trash.send2trash(file)
print("Files moved to Trash.")
`
**Output
Files moved to Trash.
**Explanation:
- Iterates through a list of files.
- Moves each file to the Trash.
- Useful for batch deletion tasks.
Handle Exceptions While Deleting Files
Exception handling can be used to manage permission errors and invalid paths during deletion.
**Example:
Python `
import send2trash
try: send2trash.send2trash("sample.txt") print("File moved to Trash.") except Exception as e: print("Error:", e)
`
**Output
If no error raised: File moved to Trash.
If error raised: Error: Permission denied
**Explanation:
- Attempts to move the file to the Trash.
- Handles errors gracefully if deletion fails.
- Prevents the program from crashing.