【问题标题】:How to get the latest file in a folder with a certain extension in python如何在python中获取具有特定扩展名的文件夹中的最新文件
【发布时间】:2022-07-18 18:01:48
【问题描述】:

我正在使用 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.")

【问题讨论】:

    标签: python


    【解决方案1】:

    我会做类似的事情:

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

    【讨论】:

      猜你喜欢
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 2018-12-23
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      相关资源
      最近更新 更多