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 can I recursively search for a file in Python

I have a program that asks the user for a path and then searches for a filename entered by the user.

I have already tried os.listdir, but it returns just the files and subdirectories directly inside the path.
It also does not search the subdirectories for the files.
I also don’t know how to use os.walk() method.

Any help on how to do that?

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 :

You can use the glob.glob() function to do the job.
Syntax:

glob.glob(path, recursive=True)

Example code:

import glob
path = "C:\\Users\\<username>\\Example"
names = glob.glob(path +  + "\\*\\*.*", recursive=True)

This searches recursively in the directory and returns a list of the files found.

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