I have my blog backup plugin configured to send backups to a folder on my Google Drive. I am looking for an application that I can set to monitor that folder and delete all but the n most recent subfolders. I have found software that will do that for files, but not for folders.

  • 1
    Take care that your backup software is not doing incremental backups. Commented Aug 19, 2017 at 13:32
  • 1
    It's not. It's complete backups each time
    – Tim
    Commented Aug 19, 2017 at 13:33
  • 1
    I don’t know Google Drive. Does the solution have to interact with the Google Drive service, or is the Google Drive integrated in your filesystem (so it acts like a normal local folder)?
    – unor
    Commented Aug 19, 2017 at 14:12
  • 1
    Google drive has a local folder with two-way sync. The solution needs only to work on the local folder and any changes will be synced to google's servers.
    – Tim
    Commented Aug 19, 2017 at 14:20
  • 1
    If your question was answered to your satisfaction, you can accept an answer by clicking on the check mark under the voting arrows. Commented Sep 1, 2017 at 17:06

1 Answer 1


The following Python script deletes all but the 3 most recently modified directories in another directory. Change the 3 to taste, and change 'mydir' to the directory you want to operate on. Uncomment the last line to actually perform the deletion. It would be reasonable to first run it with the last line still commented out to ensure everything's set up correctly.

import os, shutil

dirs = sorted((f for f in os.listdir('mydir') if os.path.isdir(f)),
    key = os.path.getmtime,
    reverse = True)[3:]
for d in dirs:
    print("Deleting", d)
#    shutil.rmtree(d)

You can run this script regularly with a cron or anacron job on Unix-likes, or Task Scheduler on Windows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.