0

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.

1
  • os.startfile('file_name') was intended to be os.startfile(file_name) Commented Oct 14, 2017 at 4:54

1 Answer 1

2

Remove the quotes around 'file_name'. Use it like below,

os.startfile(file_name)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.