File Searching using Python

PythonServer Side ProgrammingProgramming

Python can search for file names in a specified path of the OS. This can be done using the module os with the walk() functions. This will take a specific path as input and generate a 3-tuple involving dirpath, dirnames, and filenames.

In the below example we are searching for a file named smpl.htm starting at the root directory named “D:\”. The os.walk() function searches the entire directory and each of its subdirectories to locate this file. As the result we see that the file is present in both the main directory and also in a subdirectory. We are running this program in a windows OS.

Example

import os

def find_files(filename, search_path):
result = []

# Wlaking top-down from the root
for root, dir, files in os.walk(search_path):
if filename in files:
result.append(os.path.join(root, filename))
return result

print(find_files("smpl.htm","D:"))

Output

Running the above code gives us the following result −

['D:TP\\smpl.htm', 'D:TP\\spyder_pythons\\smpl.htm']
Published on 17-Oct-2019 16:12:42