Reputation: 41
I have a directory with web camera images that are constantly incrementing. I would like to use a python script to get the most recent 10 images. Currently I have the following code for getting the most recent image. I would like to decrement the file name and get the most recent 10 images and name them image_current1.jpg to image_current10.jpg.
import os
import glob
from PIL import Image
from shutil import copyfile
# variables
rawFileDir = 'C:\pictures\image00*.jpg'
mriFileName = 'C:\pictures\image_current1.jpg'
# obtain and copy most recent image
mostRecentImage = max(glob.iglob(rawFileDir), key=os.path.getctime)
copyfile(mostRecentImage,mriFileName)
Upvotes: 0
Views: 117
Reputation: 2936
You can use sorted list from glob.iglob(rawFileDir)
:
import os
import glob
from PIL import Image
from shutil import copyfile
# variables
rawFileDir = 'E:\Test\image00*.jpg'
mriFileName = 'E:\Test\image_current'
# obtain and copy most recent image
mostRecentImage = sorted(glob.iglob(rawFileDir), key=os.path.getctime)
for num, i in enumerate(mostRecentImage[:~10:-1]):
exec('copyfile(i, mriFileName + str({}) + ".jpg")'.format(num + 1))
image_current1.jpg
will be the most recent file.
Upvotes: 1
Reputation: 109696
This will provide a dictionary of the desired filenames (e.g. image_current01.jpg) and the target file.
{'image_current' + str(n).zfill(1): filename
for n, filename in enumerate(sorted((os.path.getctime(f), f)
for f in glob.glob('*.jpg'))[-10::][::-1])}
Upvotes: 0