Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Python, write a recursive function search () that takes as a parameter the na

ID: 3933657 • Letter: I

Question

In Python, write a recursive function search() that takes as a parameter the name of a file and the pathname of a folder and searches for the file in the folder and any subfolder contained within it, directly or indirectly. The function should return the pathname of the file, if found, or None (the type in Python, not the string 'None') if the file cannot be found in anywhere in the folder or any of its subfolders. You are allowed to use a loop in this function, but the main work of the function should be done using recursion. The following illustrates several searches using the test folders and directories that are listed in the question above.

Explanation / Answer

import os
def search(fileName, path):
   listOfFiles = os.listdir(path)
   for NameHere in listOfFiles:
       fullPath = os.path.join(path,fileName)
       if(os.path.isfile(fullPath)):
          if(fileNameHere == join(path,fileName)):
              print(fileNameHere)
          else:
              None
      elif(os.path.isdir(fullPath)):
          search(fileName,fullPath)
      else:
          None

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote