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

Using Python Implement function search() that takes as input the name of a file

ID: 3605335 • Letter: U

Question

Using Python

Implement function search() that takes as input the name of a file and the pathname of a folder and searches for the file in the folder and any folder contained in it, directly or indirectly. The function should return the pathname of the file, if found; otherwise, None should be returned. The below example illustrates the execution of search('file.txt', 'test') from the parent folder of folder 'test' shown in Figure 10.8.

>>> search('fileE.txt', 'test')

File: test.zip test/folder2/fileE.txt

Explanation / Answer

import os

def search(name, path):
cur_dir = os.path.dirname(os.path.realpath(__file__))
for root,dirs,files in os.walk(os.path.join(cur_dir,path)):
if name in files:
return "File: {} {}".format(name, os.path.join(root[len(cur_dir)+1:],name))

return None

'''Explanation:

os.walk can be used to traverse files in a system. It gives us a list of files in the current directory. We then check if our file is present in the list.

root[len(cur_dir)+1:] --> We want just relative path. Hence, removing the path of the current directory.

'''

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