Monday, April 21, 2025

Send File to Recycle Bin with Python - send2trash

send2trash is a Python module that provides a cross-platform way of sending files and directories to the operating system's trash or recycle bin, rather than deleting them permanently.

The module provides a simple function send2trash.send2trash() that takes a file or directory path as input and sends it to the operating system's trash or recycle bin, depending on the platform. 

C:\Users\user>pip install send2trash
Collecting send2trash
  Using cached Send2Trash-1.5.0-py3-none-any.whl (12 kB)
Installing collected packages: send2trash
Successfully installed send2trash-1.5.0

C:\Users\user>

The command pip install send2trash installs the send2trash Python module, which provides a cross-platform way of sending files and directories to the operating system's trash or recycle bin, rather than deleting them permanently.

If you run this command in your command prompt, it should start the installation process of send2trash

import send2trash as s2t

try:
    s2t.send2trash('some-report.txt')    
except:
    print('Cant\'t delete that file')

This code use the send2trash module to attempt to send a file named 'some-report.txt' to the trash or recycle bin instead of deleting it permanently.

If the send2trash() function call raises an exception (i.e., an error), the code will catch the exception with the try/except block and print a message saying that the file couldn't be deleted.

This is a safer way to delete files than using os.unlink() or os.remove(), as it allows users to recover accidentally deleted files from the trash or recycle bin.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...