Skip to content

Instantly share code, notes, and snippets.

@dmitryhd
Created November 30, 2015 12:45
Show Gist options
  • Select an option

  • Save dmitryhd/2e583eaf806b52ae0d60 to your computer and use it in GitHub Desktop.

Select an option

Save dmitryhd/2e583eaf806b52ae0d60 to your computer and use it in GitHub Desktop.
Auto deletion of old files
#!/usr/bin/env python2
import os
from glob import glob
from datetime import datetime, timedelta
root_dir = '/var/local/crm/data/launches/'
def print_oldfiles(root_dir, olddays=20, minsizemb=10):
sizesmb = []
names = []
for f in os.listdir(root_dir):
fpath = os.path.join(root_dir, f)
if os.path.isdir(fpath):
for csvfile in glob(fpath + '/*.csv'):
try:
mtime = os.path.getmtime(csvfile)
except OSError:
mtime = 0
last_modified_date = datetime.fromtimestamp(mtime)
fsizemb = os.path.getsize(csvfile)/1024/1024
if last_modified_date < datetime.now() - timedelta(days=olddays) and fsizemb > minsizemb:
#print(csvfile)
names.append(csvfile)
sizesmb.append(fsizemb)
#print(last_modified_date)
#print('{} mb'.format(fsizemb))
return names, sizesmb
def delete_files(filelist):
for fpath in filelist:
os.unlink(fpath)
if __name__ == '__main__':
files, sizes = print_oldfiles(root_dir, 30)
print('total files: {}, size: {} mb'.format(len(files), sum(sizes)))
import time
time.sleep(5)
delete_files(files)
print('files deleted!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment