Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to search everywhere within a specific directory (including sub folders) using python

basically, as the title says, I want to be able to use a python script where I give a path/directory, and a file name, and it will search all the way through the path/directory just to find the file name.

I have tried using glob.glob() however it will only search within the directory and not within subfolders and such from what I have found.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From the glob.glob() docs (emphasis mine), starting at Python 3.5:

If recursive is true, the pattern "**" will match any files and zero or more directories, subdirectories and symbolic links to directories.

So you just put ** into your pattern where you want it to expand to any subdirectories and files therein and add recursive=True as a keyword argument.

For example, given a directory structure like

a
+-b
| +-d
|   +-f
+-c
  +-e

with your current working directory being a, you can do:

>>> from glob import glob
>>> glob("**", recursive=True)
['c', 'c/e', 'b', 'b/d', 'b/d/f']

For your specific use case of searching for a filename in all subdirectories, you’d do:

>>> glob("**/f", recursive=True)
['b/d/f']

Note that ** patterns also work in pathlib.Path.glob() and pathlib paths are often more comfortable to use than the more low-level os.path and glob modules.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading