简体   繁体   中英

How can I decrement file names in python?

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)

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.

This will provide a dictionary of the desired filenames (eg 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])}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM