Delete files that are older than 10 (or x) days

Here is a simple python script to delete files from the current directory that are older than 10 days,
you probably need to customize it a little to specify the files to delete.


# run by crontab
# removes any files in current folder older than days_old days

import os, sys, time

def get_file_directory(file):
    return os.path.dirname(os.path.abspath(file))
now = time.time()
days_old = 1 #change this to how many days old files to delete
cutoff = now - (days_old * 86400)
files = os.listdir(get_file_directory(__file__))
file_path = get_file_directory(__file__)
for xfile in files:
        print("Check :" + xfile)
        if xfile.startswith('0000'):    #My Files stated with 0000 you can add other criteria here maybe xfile.endswith('.OLD')
            fullFile = os.path.join(str(file_path), xfile)
            #print("Path : " + fullFile)  Remove the comment to list all the files to be deleted
            if os.path.isfile(fullFile):
                t = os.stat(fullFile)
                c = t.st_ctime
                # delete file if older than [days_old] days
                if c < cutoff:
                    print("Will Remove " +fullFile + "to go ahead and remove the files please remove the # in the next line") #for now we will just print it
                    #os.remove(fullFile)  #comment this line to delete the files

Thanks to for the outline

Leave a Reply

Your email address will not be published.

Reload Image