Reputation: 55
I'm trying to create a MP3 player in Python and I let the user run MP3s by inputting the name of the file. The only problem is, if the user inputs an incorrect name or a name that doesn't exist... the script closes. I was wondering if there would be a way to say:
if filedoesnotexist:
skip this line of code
Here's the actual code I'm using in the script:
class player():
def player_name():
Minput= input("Insert name of mp3: ")
os.startfile("MP3_folder\\" +Minput + ".mp3")
input("Input a key to end playback: ")
os.system("TASKKILL /F /IM wmplayer.exe")
Upvotes: 1
Views: 110
Reputation: 309
If you want to simply "skip this line of code" if a user enters an incorrect file name, you could use a try
/except
block, like so:
class player():
def player_name():
Minput= input("Insert name of mp3: ")
try:
os.startfile("MP3_folder\\" +Minput + ".mp3")
except OSError:
pass
input("Input a key to end playback: ")
os.system("TASKKILL /F /IM wmplayer.exe")
If you wanted it to return back to the beginning of the loop when/if an incorrect value is entered, you could try and use a While True
loop; something like is discussed here.
Upvotes: 3