File Searching using Python


Python can search for file names in a specified path of the OS. This can be done using the os module with the walk() function. 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']

Updated on: 26-Aug-2023

32K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements