I have a folder of 1000 photos that I'd like to make a timelapse of. The photos are shot every 60 seconds, and I'd like to make a 10 minute interval timelapse. So I need to delete every 2nd to 9th photo and have it loop. For example, given 1000 photos in a folder, I'd like the script to keep photo 1, 10, 20, 30 and so on and so forth. At the end of this script, the folder should only contain 100 photos.
The following code removes every "10th" photo, which doesn't do exactly as I want:
import os
dir_to_clean = '/Users/myname/Desktop/TBD'
l = os.listdir(dir_to_clean)
for n in l[::10]:
os.unlink(dir_to_clean + '/' + n)
How do I modify this code so that it deletes every 2nd-9th photo? It should still be able to run if the folder does not have an even number of files (e.g. if it has 1005 files).
First of all, you should not depend on the underlying OS indexing to do the sorting for you - you should sort the image list yourself (hopefully their names are in a lexicographical order).
Second, once sorted, just enumerate your list and don't delete every 10th item, e.g.:
import os
dir_to_clean = '/Users/myname/Desktop/TBD'
images = sorted(os.listdir(dir_to_clean))
for i, image in enumerate(images):
if i % 10 != 0:
os.remove(os.path.join(dir_to_clean, image))
For an image list like: ["image000.jpg", "image001.jpg", "image002.jpg", "image003.jpg", ... "image035.jpg"]
this will delete all images except image000.jpg
, image010.jpg
, image020.jpg
and image030.jpg
.