Reputation: 43
I am trying to write a code which will search a mp3 file in a directory and play it. But I am getting this error. The code is
import os
file_name = raw_input("File Name: ") #file to be searched
#cur_dir = raw_input("Search Directory: ") # Dir from where search starts
can be replaced with any path
cur_dir = os.getcwd()
while True:
file_list = os.listdir(cur_dir)
parent_dir = os.path.dirname(cur_dir)
if file_name in file_list:
print ("File Exists in: "), cur_dir
#
os.startfile('file_name')
#
break
else:
if cur_dir == parent_dir: #if dir is root dir
print ("File not found")
break
else:
cur_dir = parent_dir
And the error that I am getting is this
>>>
File Name: Kalimba.mp3
File Exists in: C:\Users\MrittikaMukut\Desktop\test
Traceback (most recent call last):
File "C:\Users\MrittikaMukut\Desktop\test\search-2.py", line 16, in
<module>
os.startfile('file_name')
WindowsError: [Error 2] The system cannot find the file specified:
'file_name'
>>>
But when I run a code similar to this which randomly picks a mp3 file from a directory and plays it, it works fine. Here is the code for it.
import random,os,sys
folder=os.listdir(os.getcwd())
file=random.choice(folder)
ext3=['.mp3']
print('First random pick: '+file)
while file[-4:] not in ext3 :
print('Not an MP3 file : '+file)
file=random.choice(folder)
else:
os.startfile(file)
print('Song name: '+file)
sys.exit()
##os.startfile(random.choice(folder))
I am confused and need some help. Thank you in advance.
Upvotes: 0
Views: 3590
Reputation: 2418
Remove the quotes around 'file_name'. Use it like below,
os.startfile(file_name)
Upvotes: 2