-2

I want to get latest 3 ".jpeg" files from a folder using python I tried like

import os
import glob


path = "path of the folder\\*.jpeg"
list_of_files = glob.iglob(path) 
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)

But I got only one file as output. How to get latest 3 files from a folder?

Aakash Patel
  • 111
  • 7
  • 2
    Use this with the sorted list of files: [How to get last items of a list in Python?](https://stackoverflow.com/questions/646644/how-to-get-last-items-of-a-list-in-python) – mkrieger1 Sep 06 '20 at 06:29
  • No as latest file is giving only one file as output , not the list – Aakash Patel Sep 06 '20 at 06:31
  • you are doing max. so it will give you only one. do you want to sort in reverse order so you can get the first 3 or the regular sort so you can take the last 3? – Joe Ferndz Sep 06 '20 at 06:33
  • Yes, because that's exactly what the answerss you already received do. Are you saying they don't work? – tripleee Sep 06 '20 at 06:34

2 Answers2

0

Try the following:

import os
import glob
    
    
files_path = os.path.join("C:\\Users\\User\\Pycharmprojects\\other\\", '*') 
list_of_files = sorted(glob.iglob(files_path), key=os.path.getctime, reverse=True)
list_of_files=[i for i in list_of_files if i[-4:]=='jpeg']
latest_files = list_of_files[:3]
print(latest_files)
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
0

Just sort the list by date and pluck off the last three elements.

import os
import glob


path = "path of the folder\\*.jpeg"
latest_files = sorted(glob.iglob(path), key=os.path.getctime))
print(latest_files[-3:]
tripleee
  • 175,061
  • 34
  • 275
  • 318