How to use Glob() function to find files recursively in Python?

PythonServer Side ProgrammingProgramming

To use Glob() to find files recursively, you need Python 3.5+. The glob module supports the "**" directive(which is parsed only if you pass recursive flag) which tells python to look recursively in the directories. 


import glob
for filename in glob.iglob('src/**/*', recursive=True):

You can check the filename using whatever condition you want using an if statement. For older Python versions, you can use os.walk to recursively walk the directory and search the files. 


import os, re, os.path
pattern = "^your_regex_here$"
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
    for file in filter(lambda x: re.match(pattern, x), files):

This will match the file name to the regex you specify and print their names.

Updated on 18-Feb-2020 05:56:58