Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

file-io

Use glob.glob:

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

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)

Give this guy a try:

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