Reputation: 109
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?
Upvotes: 2
Views: 206
Reputation: 109
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
Upvotes: 0
Reputation: 71
Did you look here? https://programtalk.com/python-examples/winshell.recycle_bin/?utm_content=cmp-true or on the winshell docs for the recycle bin here: https://winshell.readthedocs.io/en/latest/recycle-bin.html
There is an example of deleting files, sorted by their recycle_date. I am sure you can use this to do what you want.
def test_delete(self):
self.assertFalse(os.path.exists(self.tempfile))
recycle_bin = winshell.recycle_bin()
newest = sorted(recycle_bin.versions(self.tempfile), key=lambda item: item.recycle_date())[-1]
newest_contents = b("").join(newest.contents())
recycle_bin.delete_file(self.tempfile)
self.assertTrue(os.path.exists(self.tempfile))
self.assertEquals(open(self.tempfile, "rb").read(), newest_contents)
Upvotes: 0