I hate when my desktop gets cluttered with files. I found myself spending far too much time once a week sifting through them all and sorting them into folders that I should’ve put them in to begin with, all so my desktop could be clean, housing only a few select folders with which I interact daily. So I wrote a little python script that automatically cleans up my desktop for me. It scans all visible non-directories on my Desktop and sorts them by creation date, then throws them into a single folder.

Personally, I liked the option of putting it on cron to run once a day as it’s rare for me to shut down my machine. But if you want, you can easily add a Login Hook to Mac OSX to do this for you each time you login.

Crontab:
On Mac OSX, to check your cron run the command

crontab -e

The Hook:


sudo defaults write com.apple.loginwindow LoginHook /path/to/script

And here’s the script:


import os, time, datetime, shutil
from time import strftime
from shutil import move

desktop_path = "/Users/your_username_here/Desktop/"
archive = "Desktop-Archives" #will be created if it doesn't already exist, so feel free to change.

def Main():
	try:
		clean()
	except KeyboardInterrupt:
		print("\r\n::: Caught quit signal from interpreter")

def clean():
	if __name__ == '__main__':
		global desktop_path
		global archive
		if os.path.exists(desktop_path+archive) == False:
			os.mkdir(desktop_path+archive)
		dirList = os.listdir(desktop_path)
		for fname in dirList:
			if os.path.isdir(desktop_path+fname) == False:

				stat = os.stat(desktop_path+fname)
				created = os.stat(desktop_path+fname).st_mtime
				fileyear = str(time.gmtime(created).tm_year)
				filemonth = time.gmtime(created).tm_mon
				if filemonth < 10:
					filemonth = "0" + str(filemonth)
				filetime = str(fileyear) + "_" + str(filemonth)
				archivedir = desktop_path+archive+"/"+filetime
				if os.path.exists(archivedir) == False:
					os.mkdir(archivedir)
				movefile(fname,archivedir)

def movefile(fname, archivedir):
	global desktop_path
	if "." not in fname[0]:
		if os.path.exists(archivedir+"/"+fname) == False:
			shutil.move(desktop_path+fname,archivedir)

Main()

The script puts your files into a folder on your Desktop defined in the variable at the top. Within the Desktop folder the files will be organized by the file's creation date.

Enjoy!