1

I wanted to write a python code that when given a string(name of the mp3 file to be searched), it would search the directory matching the given string with the file names. When found, it would open and play it.

I have a code that searches a given directory for the given string. Is it possible to modify this code to achieve the above mentioned task? Thank you. `

#Import os module
import os

# Ask the user to enter string to search
search_path = input("Enter directory path to search : ")
file_type = input("File Type : ")
search_str = input("Enter the search string : ")

# Append a directory separator if not already present
if not (search_path.endswith("/") or search_path.endswith("\\") ): 
        search_path = search_path + "/"

# If path does not exist, set search path to current directory
if not os.path.exists(search_path):
        search_path ="."

# Repeat for each file in the directory  
for fname in os.listdir(path=search_path):

   # Apply file type filter   
   if fname.endswith(file_type):

        # Open file for reading
        fo = open(search_path + fname)

        # Read the first line from the file
        line = fo.readline()

        # Initialize counter for line number
        line_no = 1

        # Loop until EOF
        while line != '' :
                # Search for string in line
                index = line.find(search_str)
                if ( index != -1) :
                    print(fname, "[", line_no, ",", index, "] ", line, sep="")

                # Read next line
                line = fo.readline()  

                # Increment line counter
                line_no += 1
        # Close the files
        fo.close()
  • Once you've found the file, `os.startfile('filename.mp3')` will play it. – Evan Nowak Oct 12 '17 at 04:30
  • Possible duplicate of [Playing mp3 song on python](https://stackoverflow.com/questions/20021457/playing-mp3-song-on-python) – Abdul Rauf Oct 12 '17 at 04:48
  • So using os.startfile I will be able to play the MP3 right? Or will I need pygame, pyglet or any other media modules for python? – Mukut Mukherjee Oct 12 '17 at 05:38
  • Use `glob.glob('*.mp3')` to get a list of matching files. Use `os.path.join()` to correctly join paths together without worrying about slash or backslashes. – Martin Evans Oct 12 '17 at 08:08
  • This is irrelevant to your question, but something to think about in the future when asking questions; don't include comments that explain what a line of code does. The line `import os` does not need a comment saying "Import os module" and `line_no += 1` does not need a comment saying "Increment line counter". It just introduce noise and makes it more difficult to read. Use comment when you feel you need to explain your logic instead. Someone who understand code don't need comments explaining the code and someone who don't understand the code can't help you. – Ted Klein Bergman Oct 12 '17 at 15:26
  • @MukutMukherjee It will play the MP3 using the default program on your computer. – Evan Nowak Oct 12 '17 at 22:05
  • @EvanNowak I am getting this error when using os.startfile() - WindowsError: [Error 2] The system cannot find the file specified: 'file_name'.Shall I start a new thread? – Mukut Mukherjee Oct 13 '17 at 14:54

1 Answers1

1

This code is a little different but works the best for the above mentioned problem.

!/usr/bin/env python3

import os
import random
import sys

rdm = raw_input("Would you let me make a choice? 0 or 1: ")

#cur_dir = os.getcwd()

if rdm == '1':
    print("Playing random song")
    folder=os.listdir(os.getcwd()) #To randomly play a song
    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()

else:
    if rdm == '0':
        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