如何在python中获得具有特定扩展名的文件夹中的最新文件



我正在使用python的虚拟助手。当我让他播放最近下载的音乐时,他应该搜索最近的音乐文件然后播放。但是,这就是问题出现的地方。还有一些其他的文件,其他的'mp4'。所以,它每次打开一个图像。我可以删除或移动该文件,但我不希望我的用户在使用它时发生这种情况。所以我试着写一个脚本,自动搜索最新的文件与特定的扩展名和播放。

下面是我的代码:-
elif 'play downloaded music' in query or 'play downloaded song' in query or 'play that song' in query or 'play the downloaded song' in query or 'play the downloaded music' in query:
try:    
latest_song = os.path.join(music_path, (max([os.path.join(music_path, basename) for basename in (os.listdir(music_path))], key=os.path.getctime)))
os.startfile(latest_song)
holdon()
except:
print("Sorry! No song found.")
speak("Sorry! No song found.")

我会做类似的事情:

import glob
import os
list_of_files = glob.glob('/path/to/folder/*.mp4') # * means all if need specific format then *.mp4 in your case
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)

或者甚至像这样:

import fnmatch
import os
print(max([file for file in os.listdir('.') if fnmatch.fnmatch(file, '*.mp4')], key=os.path.getctime))

最新更新