James John – Software Engineer

Recursively Delete Files Based on Time Old Using Python

As a system admin, was stuck one day looking for a way to delete old files and it brought me to this code. This short code will delete files recursively if directory provided as the argument, if it’s a file, it just deletes the file if it matches the given time frame

#!/usr/bin/env python
import os
import datetime

def delete_files( dir, min_old, comparism = True ):
	min_old = int( min_old )

	if os.path.isdir( dir ):	#If directory was provided
		for root, Dir, file in os.walk( dir ):	#Walk through the directory and fetch files
			for files in file:
				files = os.path.join( root, files )
				if os.path.isfile( files ):	#If finally it grabs a file, deal with it
					if comparism:
						if get_age( os.path.getmtime( files ) ) >= min_old:
							os.remove( files )
					else:
						if get_age( os.path.getmtime( files ) ) <= min_old:
							os.remove( files )
	elif os.path.isfile( dir ): 	#Else it was a file was provided, still lets work with it
		if comparism:	#Deal with it
			if get_age( os.path.getmtime( dir ) ) >= min_old:
				os.remove( dir )
		else:
			if get_age( os.path.getmtime( dir ) ) <= min_old:
				os.remove( dir )
	else:
		print 'Directory not found, so nothing done'

def get_age( min ):
	min = datetime.datetime.fromtimestamp( int( min ) )
	today = datetime.datetime.now()
	diff = today - min 
	return diff.seconds

So with the above code, you can just use this function to do what you want

delete_files( 'path/to/file/or/directory', 500 )

So I’m deleting files of 500seconds old on earth.

I guess this helps

James John

Software Engineer