Skip to content

Instantly share code, notes, and snippets.

@n-eq
Last active May 13, 2017 10:23
Show Gist options
  • Save n-eq/7acd2e9066121d18776256f4926deeb8 to your computer and use it in GitHub Desktop.
Save n-eq/7acd2e9066121d18776256f4926deeb8 to your computer and use it in GitHub Desktop.
Delete rotten downloads on a Window host
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 25 09:11:46 2017
@author: marrakchino
based on the original idea (and implementation) of Cory Engdahl (https://www.quora.com/As-a-programmer-what-tasks-have-you-automated-to-make-your-everyday-life-easier/answer/Cory-Engdahl?srid=utoTd)
"""
import os
import time
import shutil
DELETE_ALWAYS = ('.tor', '.torrent', '.ico', '.ics', '.aux', '.cap', '.dvi', '.tmp')
DELETE_NEVER = ()
DELETE_AFTER = 8760 # number of hours, here: 8760 hours = 365 days, configurable
DELETE_PATH = 'C:\\Users\\ELQATIB\\Downloads\\' # Put the path to the directory you want to clean
def rotten_file(file):
name, ext = os.path.splitext(file)
return (time.time() - os.path.getmtime(DELETE_PATH +
file) > (DELETE_AFTER*3600))
def precious_file(file):
name, ext = os.path.splitext(file)
return ext in DELETE_NEVER
def worthless_file(file):
name, ext = os.path.splitext(file)
return ext in DELETE_ALWAYS
# recursively count the number of files in a given directory
def count_files(directory):
if os.path.isfile(directory):
return 1
else:
number_of_files = 0
for file in os.listdir(directory):
number_of_files += count_files(os.path.join(directory, file))
return number_of_files
# files to evaluate
contents = []
# omit hidden files
for file in os.listdir(DELETE_PATH):
if not file.startswith('.'):
contents.append(file)
print('[log] Cleaning Directory')
total_size_of_deleted_files=0
number_of_deleted_files=0
for file in contents:
fullpath = DELETE_PATH + file
# print("[log] full path: " + fullpath)
if (not rotten_file(file) and not worthless_file(file)):
continue
elif not precious_file(file):
if os.path.isfile(fullpath):
total_size_of_deleted_files += os.path.getsize(fullpath)
number_of_deleted_files += 1
os.remove(fullpath)
# print('[log] deleting file %s', file)
elif os.path.isdir(fullpath):
number_of_deleted_files += count_files(fullpath)
shutil.rmtree(fullpath)
# print("[log] deleting directory" + file)
print("Results: Deleted %d files, free'd %d MB." % (number_of_deleted_files, total_size_of_deleted_files / 10 ** 6))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment