Create a function “find_file” that accepts a full directory path parameter (i.e.
ID: 3841686 • Letter: C
Question
Create a function “find_file” that accepts a full directory path parameter (i.e., C:Userscs401DesktopDocs) and a file name parameter (i.e., MyFile.txt) that recursively searches all folders and subfolders under the provided path for the specified filename. When found, the full file pathname should be printed. Note there may be multiple files within a folder structure that match the specified name. If the file is not found, nothing should be printed. If listing the files in a folder results in a PermissionError – skip that folder.
CODE IN "PYTHON"
Sample output:
find_file("C:\Users\cs401\Desktop\Docs", "build.xml")
C:UserssdDesktopDocsArtArraysuild.xml
C:UserssdDesktopDocscommClientuild.xml
C:UserssdDesktopDocshola105uild.xml
Explanation / Answer
This code is written in Python 3.6.1 shell:
import os
def find_all(file_name, dir_path):
file_list = []
for root, dirs, files in os.walk(dir_path):
if file_name in files:
file_list.append(os.path.join(root, file_name))
return file_list
dir_path = input("Enter directory to check file:")
file_name = input("Enter filename:")
print(find_all(file_name,dir_path))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.