Best Practice to Python Delete File With Sending It to Recycle Bin in Windows 10 – Python Tutorial

By | October 9, 2019

In python, we can use os.remove() function to delete a file permanently, however, we can not find the deleted file in our recycle bin. If you have deleted wrong files? Which will be a big problem. In this tutorial, we will introduce how to delete a file with sending it to our recycle bin in win 10 with python.

Import libraries

from win32com.shell import shell,shellcon
import os

Create a python function to delete a file to recycle bin

Here we write an python function to delete files.

def deltorecyclebin(filename):
    if not os.path.exists(filename):
        return True
    res= shell.SHFileOperation((0,shellcon.FO_DELETE,filename,None, shellcon.FOF_SILENT | shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION,None,None))
    if not res[1]:
        os.system('del '+filename)

How to use this function?

You can call this function like this:

deltorecyclebin('home.png')

Run this python script, you will find home.png file in your recycle bin.

python delete file to recycle bin

Leave a Reply