Glob is a general term used to define techniques to match specified patterns according to rules related to unix shell.
In python, the glob module is used to retrieve files matching a speific pattern.
Using glob() function to find files recursively
We can use the function glob.glob() or glob().iglob() directly from glob module to path recursively
from inside the directions and sub directions
syntax:
glob.glob(pathname, *,recursive=False)
glob.iglob(pathname, *,recursive=False)
when recursive is set True”**”followed by path seperator(‘./**/’)will match any files or directories.
# python program to find files # recursively using python import glob # Returns a list of names in list files. print("Using glob.glob()") files = glob.glob('/home/geeks/Desktop/gfg/**/*.txt', recursive = True) for file in files: print(file) #It returns an iterator which will be printed simultaneously. print("\nUsing glob.iglob()") for filename in glob.iglob('/home/geeks/desktop/gfg/**/*.txt', recursive = True): print(filename)
Output:
Using glob.glob() /home/geeks/Desktop/gfg/data.txt /home/geeks/Desktop/gfg/myfile.txt /home/geeks/Desktop/gfg/gfg.txt /home/geeks/Desktop/gfg/Test/C/test2.txt /home/geeks/Desktop/gfg/Test/A/A1/test1.txt Using glob.iglob() /home/geeks/desktop/gfg/data.txt /home/geeks/desktop/gfg/myfile.txt /home/geeks/desktop/gfg/gfg.txt /home/geeks/desktop/gfg/Test/C/test2.txt /home/geeks/desktop/gfg/Test/A/A1/test1.txt