Skip to content

Instantly share code, notes, and snippets.

@haryp2309
Last active July 7, 2024 13:26
Show Gist options
  • Save haryp2309/e00b7e303c9090bedbde5a4001b98502 to your computer and use it in GitHub Desktop.
Save haryp2309/e00b7e303c9090bedbde5a4001b98502 to your computer and use it in GitHub Desktop.
Auto Trash Downloads MacOS Python Script
# Trashing implementation is based on https://github.com/arsenetar/send2trash
# Requries pyobjc-library to be installed ("python3 -m pip install pyobjc")
import os
import time
from pathlib import Path
from subprocess import run
from Foundation import NSFileManager, NSURL
def notify(title, text):
run(["osascript", "-e", f'display notification "{text}" with title "{title}"'])
MAX_DAYS = 3
current_time = time.time()
dir_path = Path.home() / "Downloads"
for f in os.listdir(dir_path):
f_full_path = dir_path / f
creation_time = os.path.getctime(f_full_path)
if (current_time - creation_time) // (24 * 60 * 60) >= MAX_DAYS:
file_url = NSURL.fileURLWithPath_(str(f_full_path))
op_result = NSFileManager.defaultManager().trashItemAtURL_resultingItemURL_error_(
file_url, None, None
)
if not op_result[0]:
print(
f"Failed to trash '{file_url}'. Reason: {op_result[2].localizedFailureReason()}"
)
print(f"Successfully trashed '{file_url}'.")
notify("Downloads Cleaner", "Finished successfully!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment