Search For A File Using Python

If you are a coder, then surely you must have come across a requirement wherein you need to search for a file in a given directory.

Now, this directory could be any directory — it could be your immediate parent directory or it could be a grand parent.

In this article, I’ll explain to you about how can you search for a file in a given directory using Python.

Required Package

To perform file search, we only need a package named os and this can be imported using below line of code:

import os

Code To Search A File

Here are the few lines of code to perform this task,

rootDir = “C:\\Py_Channel”
fileToSearch = “activate.bat”

for relPath,dirs,files in os.walk(rootDir):
   if(fileToSearch in files):
      fullPath = os.path.join(rootDir,relPath,fileToSearch)
      print(fullPath)

In the above code, rootDir is the top-level directory in which we want to perform search and fileToSearch is holding the file name, we want to search.

os.walk() help us to traverse the directory hierarchy for us and returns three tuples,

  • relative path
  • directories
  • files

If you would like to have a complete code walk through, do not forget to check out my YouTube video uploaded here.