Script to count images in a folder counts 30% to much

I have a picture frame connected to HASS.IO and I want to send the number of current images on display to HA via MQTT. That part is (now) easy.

I am using a Python script on the picture frame which I guess is right but the number of counted images is not.

#!/usr/bin/env python3

import os

jpgCounter = 0
for root, dirs, files in os.walk("/home/pi/Pictures/frame"):
    for file in files:    
        if file.endswith('.jpg'):
            jpgCounter += 1

print(jpgCounter)

It returns about 30% more images than there are in the various directories. Where is the mistake?

I found the solution and will document it here in case somebody struggles with the same.

When you access the RPI from a Mac, macOS will write all kind of additional stuff in the directory which is hidden, stuff like directories “.AppleDouble”. In addition, I am using Resilio Sync for image syncing which also adds some nasty stuff.

To get the net number of files, the script must be:

#!/usr/bin/env python3

import os

searchdir = r"/home/pi/Pictures/frame"  # your search starts in this directory (your root) 

count = 0
for root, dirs, files in os.walk(searchdir):
    for name in files:
        ext = os.path.splitext(name)[1].lower()
        if ext in ('.jpg') and not '.AppleDouble' in root and not name.startswith('.') and not '.sync' in root:  # check the extension
            count += 1

print('\ntotal number of .jpg files found: %d' % count)

Hi, thanks for the info.
How have you got a picture frame attached, Id be interested to do the same with security camera still shots, but not on a photo frame but the main display

Hi @stratplayer: The photo frame is a separate Raspberry Pi with a monitor. It is controlled via MQTT by HASS.IO. There seem to be a number of example of people here on the forum that use the security camera feed to show in lovelace but it’s different from my application.