pythonfile-managementrecycle-binpython-winshell

How do I delete only older files from Recycle Bin in Python?


I am trying to make a program that deletes files that were deleted a certain number of days ago from the recycling bin. I know there is a simple way to empty the recycling bin with winshell, but I only want to delete older files. I know there is a simple way to do this in normal folders, but I don't know how to get the path without unhiding protected operating system files (which I don't want to do).

How can I do this?


Solution

  • Ended up coming up with this solution, it does require error handling if you are trying to restore or delete certain files such as Desktop shortcuts. I am still open to finding a better solution.

    import os
    import winshell
    import datetime
    import shutil
    
    DAYS = 30
    
    midnight = datetime.datetime.now(datetime.timezone.utc).replace(hour=0, minute=0, second=0) # get midnight of current day
    cutoffDate = midnight - datetime.timedelta(days=DAYS) # calculate cutoff date
    
    for item in winshell.recycle_bin():
        if item.recycle_date() <= cutoffDate: # if item was deleted 30 or more days ago
            try:
                winshell.undelete(item.original_filename()) # restore file to its original location
            except Exception as e:
                print(f"Error restoring {item.original_filename()}: {e}") # unable to restore file
            try:
                # if item is a folder, permanently delete it
                if os.path.isdir(item.original_filename()):
                    shutil.rmtree(item.original_filename())
                # if item is a file, permanently delete it
                else:
                    os.remove(item.original_filename())
            except Exception as err:
                print(f"Error deleting {item.original_filename()}: {err}") # unable to remove folder/file