0

I am trying to get a list of the 5 most recently imported pictures into a folder to feed into a function loading them into a contact sheet.

I have a program bringing in files and it uses a counter to name them 00001, 00002 etc... I was thinking something like

while blah:
N = '0000'x
x = x+1

but this breaks down when you get above 10, because now it's 00010.

I feel like I should be able to figure this out, but it's totally escaping me.

on the other hand, if I could just have the program load the X newest files into the function, that would also work great.

Image names are run through this formula.

 imgs = [Image.open(fn).resize((photow,photoh)) for fn in fnames]

so I think they need to be in the format ('00001.jpg','00002.jpg','00003.jpg'.....)

thanks for help.

jeffpkamp
  • 2,732
  • 2
  • 27
  • 51

2 Answers2

2
>>> '{:05}'.format(10)
00010

As for sorting files based on this numbering:

import os

# List all files in current directory
files = os.listdir('.')
recent_images = sorted(files)[-5:]
Maciej Gol
  • 15,394
  • 4
  • 33
  • 51
1

on the other hand, if I could just have the program load the X newest files into the function, that would also work great.

You can use os.path.getmtime and sorted to get a list of most recently changed file:

>>> import os
>>> sorted(filenames, key=lambda x:os.path.getmtime(x), reverse=True)[:5]

Related: How to get file creation & modification date/times in Python?

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504