Thursday, June 9, 2016

PI Critter Cam Day 8: Looping through our pictures and deleting old ones

Our slow progression continues. We're still building a critter cam with our raspberry pi that'll take pictures of critters in my backyard when detected.

Today:  going through all the pictures already taken and deleting ones that have reached a certain age.  We're doing this to avoid the tiny hard drive on the Pi from getting too full.

In Python, there's an os package that allows you to create a list of files and folders.  If we create a list of files in our critter cam folder, we can iterate through it, checking the age of the pictures and deleting the ones that are too old.

First, we create a list of files in our critter folder using the listdir function.

critter_path = '/home/pi/Pictures/critter_cam/'
os.listdir(critter_path)

Next, we go through the list and check out how old the file is (building on what we learned last time by using the datetime module):

import datetime

for x in os.listdir(critter_path):
print(datetime.datetime.fromtimestamp(os.path.getmtime(critter_path + x)))

Building on that, if the file is older than two weeks, delete it.

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 ' + x)

Now let's put it all together.

#import our needed modules
import os.path, datetime

#folder where we keep our critter pics
critter_path = '/home/pi/Pictures/critter_cam/'

#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 ' + x)

Awesome!  Next up, we'll start working on getting the Pi to take a picture automatically when it sees an animal through the camera.

No comments: