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

<br />
#!/usr/bin/env python<br />
import os<br />
import datetime</p>
<p>def delete_files( dir, min_old, comparism = True ):<br />
	min_old = int( min_old )</p>
<p>	if os.path.isdir( dir ):	#If directory was provided<br />
		for root, Dir, file in os.walk( dir ):	#Walk through the directory and fetch files<br />
			for files in file:<br />
				files = os.path.join( root, files )<br />
				if os.path.isfile( files ):	#If finally it grabs a file, deal with it<br />
					if comparism:<br />
						if get_age( os.path.getmtime( files ) ) &gt;= min_old:<br />
							os.remove( files )<br />
					else:<br />
						if get_age( os.path.getmtime( files ) ) &lt;= min_old:<br />
							os.remove( files )<br />
	elif os.path.isfile( dir ): 	#Else it was a file was provided, still lets work with it<br />
		if comparism:	#Deal with it<br />
			if get_age( os.path.getmtime( dir ) ) &gt;= min_old:<br />
				os.remove( dir )<br />
		else:<br />
			if get_age( os.path.getmtime( dir ) ) &lt;= min_old:<br />
				os.remove( dir )<br />
	else:<br />
		print 'Directory not found, so nothing done'</p>
<p>def get_age( min ):<br />
	min = datetime.datetime.fromtimestamp( int( min ) )<br />
	today = datetime.datetime.now()<br />
	diff = today - min<br />
	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