Sunday, June 12, 2016

PI Critter Cam Day 9: Turn the Delete Files Process into a Function

While I'm at it and before I move on to figuring the motion sensor part of our project, I'm going to really quickly turn the portion of the code that checks for and deleting old files into a function with the python code.  This way, I can keep it separate from the rest of the process and call it wherever I want.

It's pretty easy to do this.  You can just define it like so.
def delete_old_files():
    #create our expiration date
    current_date = datetime.datetime.today()
    #The variable representing the duration we want to subtract to create our expiration date.
    y = datetime.timedelta(weeks = 2)
    #And create our expiration date variable.
    exp_date = current_date - y
    #Create a list of picture files in our critter folder and delete the pics that are older than our expiration date.
    for x in os.listdir(critter_path):
        
        if datetime.datetime.fromtimestamp(os.path.getmtime(critter_path + x)) < exp_date:
            os.remove(critter_path + x)
            print('removing ' + critter_path + x) 
        else: print('not old enough to delete: (' + critter_path + x + ')')

and when you want to use it, you just put in the following:  delete_old_files()

I'm not really sure where I want to do this check.  Having it as a function allows me to put off the decision.

No comments: