-1

I am working on a virtual assistant using python. When I ask him to play the recently downloaded music, he is supposed to search for the recent music file and then play it. But, this is where the problem arises. There are also some other files other the 'mp4'. So, it open an image every time. I can delete or move that file, but I don't want to happen it with my users when they use it. So I trying to write a script that automatically searches the latest file with a specific extension and the play.

Here is my code:-

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.")

1 Answers1

1

I would do something similar to this:

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)

or even something like this:

import fnmatch
import os
print(max([file for file in os.listdir('.') if fnmatch.fnmatch(file, '*.mp4')], key=os.path.getctime))
Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50
  • It is showing this error:- ValueError: max() arg is an empty sequence – Yash Choudhary Jul 18 '22 at 10:05
  • Have you updated '/path/to/folder/*.mp4' to reflect the correct directory for you. It will return an error if the list returned by list_of_files is empty so I would do two things. 1) make sure that the directory is correct and 2) handle the exception with a try: except: or if len(list_of_files) to only do something with the list if it exists if there is any chance the directory could be empty. – Johnny John Boy Jul 18 '22 at 10:08
  • Yes! I updated it. – Yash Choudhary Jul 18 '22 at 10:09
  • I still didn't work bro. – Yash Choudhary Jul 18 '22 at 10:11
  • What's the error? max() is empty literally means the list is empty so it's either the directory is empty or you have no files ending mp4... I've tested this locally and it works. – Johnny John Boy Jul 18 '22 at 10:12
  • But, it's not working. I have checked the directory – Yash Choudhary Jul 18 '22 at 10:16
  • The most likely scenario is that you have the path wrong and it's returning no files. I've just updated the example with another way of doing the exact same thing. To work this out you need to print the results of list_of_files and figure out why it's empty, that's the issue and it's nothing to do with the line finding the most recent file. – Johnny John Boy Jul 18 '22 at 10:27