Skip to content

Instantly share code, notes, and snippets.

@pcnoic
Created October 3, 2021 15:58
Show Gist options
  • Save pcnoic/30b2c0a3e86d7a5d48014571f9e8abb9 to your computer and use it in GitHub Desktop.
Save pcnoic/30b2c0a3e86d7a5d48014571f9e8abb9 to your computer and use it in GitHub Desktop.
Delete files older than 3 months by parsing dates in filename
#!/usr/bin/env python3
# Simple script to delete files older than 3 months.
# Usage: ./clean.py <path-of-dir-to-clean>
import os
import sys
import re
import datetime
from datetime import datetime as dt
from dateutil.relativedelta import relativedelta
monitor_dir = sys.argv[1]
today = datetime.datetime.now()
delete_policy_date = today + relativedelta(months=-3) # Getting the date of 3 months ago
print("Cleaning: " + monitor_dir)
# Using path walking from: https://stackoverflow.com/questions/18394147/recursive-sub-folder-search-and-return-files-in-a-list-python
result = [os.path.join(dp, f) for dp, dn, filenames in os.walk(
monitor_dir) for f in filenames if os.path.splitext(f)[1] == '.csv']
# Parsing for date and deleting based on parsed date.
for name in result:
date = re.search("([0-9]{4}\-[0-9]{2}\-[0-9]{2})", name).group()
print(date)
if dt.strptime(date, "%Y-%m-%d") < delete_policy_date:
print("[DEBUG] Deleting file: ", name)
os.remove(name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment