How to find newest file with .MP3 extension in directory?

I am trying to find the most recently modified (from here on out 'newest') file of a specific type in Python. I can currently get the newest, but it doesn't matter what type. I would like to only get the newest MP3 file.

Currently I have:

import os
  
newest = max(os.listdir('.'), key = os.path.getctime)
print newest

Is there a way to modify this to only give me only the newest MP3 file?


Solution 1:

Use glob.glob:

import os
import glob
newest = max(glob.iglob('*.[Mm][Pp]3'), key=os.path.getctime)

Solution 2:

Assuming you have imported os and defined your path, this will work:

dated_files = [(os.path.getmtime(fn), os.path.basename(fn)) 
               for fn in os.listdir(path) if fn.lower().endswith('.mp3')]
dated_files.sort()
dated_files.reverse()
newest = dated_files[0][1]
print(newest)

Solution 3:

Give this guy a try:

import os
print max([f for f in os.listdir('.') if f.lower().endswith('.mp3')], key=os.path.getctime)