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. 

example

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

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. 

example

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):
        print(file)

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

raja
Published on 27-Dec-2017 15:19:28
Advertisements