python downloads cleanup
We understand how hard it can be to maintain your downloads directory. We developed a python script to delete any file within the downloads directory that has been modified more than 7 days ago. After reading this tutorial, you will know how to delete all files within a directory and execute the script on schedule using MacOS.

Develop cleanup script

At a high level our script must do the following:

Navigate to our Downloads directory or another directory of choice


import os
import glob
import time
import sys
import datetime
import logging


path = '/path/to/Downloads/'
os.chdir(path)

Search for files that meet our criteria

for filename in glob.glob('*'):
filename = os.path.join(path, filename)
mod_date = datetime.date.fromtimestamp(os.stat(filename).st_mtime)

Delete all files that have been modified more than 7 days ago

if mod_date < (datetime.date.today() - datetime.timedelta(days=7)):
try:
if os.path.isfile(filename):
os.remove(filename)
except:
pass

In the first step we are navigating to the directory we want to cleanup using its absolute path. Then we use the glob module to filter files according to our needs. In this case, we are getting everything except for hidden files. On a mac, this ensures that our .DS_store and .localized files are not removed. The glob module returns the filenames with their relative path. Therefore, we append the directory path to ensure we don’t have any issues deleting the files. We retrieve the modification date for each file and if the date is more than 7 days prior to the current date we delete the file.

A working copy of the cleanup script along with instructions can be found in our GitHub repo.

Schedule cleanup process

Now that we have a working script that removes files from our Downloads directory. Let’s schedule it to run every Sunday at 3:30AM. Using a mac we need to create a plist file. You can find an example plist file in our GitHub repo.  In this file, you can edit the frequency for which you would like this script to run. After edits are made, you can place the file in your ~/Library/LaunchAgents directory. In order to finalize the scheduling process you must execute the following command:


launchctl start nameOfPlistFile

Conclusion

We have successfully developed and scheduled a cleanup script to remove files from a specific directory on our system. In this scenario, we have chosen to cleanup our downloads directory. However, this same script can be used for any directory. If you have questions or know of an easier way to implement this solution, please contact us.

Has your downloads directory become hard to maintain? Create a python script to clean it up.
Tagged on: