Automating my photo backup with a simple Python script
I take a lot of photos on my phone, and up until recently, my backup strategy was just "copying the DCIM folder to an external drive once a month." As you can imagine, this led to duplicate files, missing photos, and a general mess.
I wanted a simple solution that didn't involve paying for cloud storage or setting up complex software like Nextcloud. So, I wrote a quick Python script to handle the organization for me.
The Logic
The script does three things:
- Scans a source folder for images (like
.jpg,.png,.heic). - Reads the EXIF data (the date the photo was actually taken).
- Moves the file into a folder structure like
Year/Month/.
The Code
I used Python with the Pillow library to read the EXIF data. Here is the core function:
from PIL import Image
import os
def get_date_taken(path):
try:
img = Image.open(path)
exif = img._getexif()
if exif:
# Tag 36867 is DateTimeOriginal
return exif.get(36867)
except Exception:
pass
return None
It's not the most robust piece of software I've ever written, but it works. If a photo doesn't have EXIF data, the script just uses the file's creation date as a fallback.
The Result
Now I just plug my phone into the server, run the script, and all my photos are neatly organized. It took about an hour to write, but it's saved me a lot of headaches.
(The rest of the article would contain the full script and instructions on how to schedule it with a cron job).