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

Question:

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?

Asked By: Butters

||

Answers:

Use glob.glob:

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

Give this guy a try:

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

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)
Answered By: Kevin Vincent
for file in os.listdir(os.getcwd()):
    if file.endswith(".mp3"):
        print "",file
        newest = max(file , key = os.path.getctime)
        print "Recently modified Docs",newest
Answered By: Arjun Krishna

For learning purposes here my code, basically the same as from @Kevin Vincent though not as compact, but better to read and understand:

import datetime
import glob
import os

mp3Dir = "C:/mp3Dir/"
filesInmp3dir = os.listdir(mp3Dir)

datedFiles = []
for currentFile in filesInmp3dir:
    if currentFile.lower().endswith('.mp3'):
        currentFileCreationDateInSeconds = os.path.getmtime(mp3Dir + "/" + currentFile)
        currentFileCreationDateDateObject = datetime.date.fromtimestamp(currentFileCreationDateInSeconds)
        datedFiles.append([currentFileCreationDateDateObject, currentFile])
        datedFiles.sort();
        datedFiles.reverse();

print datedFiles
latest = datedFiles[0][1]
print "Latest file is: " + latest
Answered By: Michael S.

Here’s a slightly more object-oriented version of @falsetru’s answer that uses the pathlib module. Another difference is, unlike his, it finds the most recently modified (not created) file.

Use Path.glob():

import os
from pathlib import Path

newest = max(Path('.').glob('*.[Mm][Pp]3'), key=os.path.getmtime)
Answered By: martineau
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.