Python:在目录中find带有.MP3扩展名的最新文件

我正在尝试在Python中查找特定types的最近修改过的(从这里出来的'最新')文件。 我现在可以得到最新的,但是什么types并不重要。 我只想得到最新的MP3文件。

目前我有:

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

有没有办法修改这只给我只有最新的MP3文件?

使用glob.glob :

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

假设你已经导入了操作系统并定义了你的path,这将起作用:

 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) 

给这个家伙一个尝试:

 import os print max([f for f in os.listdir('.') if f.lower().endswith('.mp3')], key=os.path.getctime) 
 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