Подтвердить что ты не робот

Python: найдите новый файл с расширением .MP3 в каталоге

Я пытаюсь найти последний модифицированный (отсюда "самый новый" ) файл определенного типа в Python. В настоящее время я могу получить новейшее, но неважно, какой тип. Я хотел бы получить только самый новый MP3 файл.

В настоящее время у меня есть:

import os

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

Есть ли способ изменить это, чтобы дать мне только самый новый MP3 файл?

4b9b3361

Ответ 1

Используйте glob.glob:

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

Ответ 2

Предполагая, что вы импортировали os и определили свой путь, это будет работать:

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)

Ответ 3

Попросите этого парня попробовать:

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

Ответ 4

В целях обучения здесь мой код, в основном такой же, как у @Kevin Vincent, хотя и не такой компактный, но лучше читать и понимать:

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

Ответ 5

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