Glob is a general term used to define techniques to match specified patterns according to rules related to Unix shell. Linux and Unix systems and shells also support glob and also provide function
glob() in system libraries.
In Python, the glob module is used to retrieve files/pathnames matching a specified pattern. The pattern rules of glob follow standard Unix path expansion rules. It is also predicted that according to benchmarks it is faster than other methods to match pathnames in directories. With glob, we can also use wildcards
("*, ?, [ranges]) apart from exact string search to make path retrieval more simple and convenient.
Note: This module comes built-in with Python, so there is no need to install it externally.
Using Glob() function to find files recursively
We can use the function
glob.iglob() directly from glob module to retrieve paths recursively from inside the directories/files and subdirectories/subfiles.
glob.glob(pathname, *, recursive=False)
glob.iglob(pathname, *, recursive=False)
Note: When recursive is set
**” followed by path separator
('./**/') will match any files or directories.
For older versions of python:
The most simple method is to use os.walk() as it is specifically designed and optimized to allow recursive browsing of a directory tree. Or we can also use os.listdir() to get all the files in directory and subdirectories and then filter out.
Let us see it through an example-
./src/add.c ./src/subtract.c ./src/sub/mul.c ./src/sub/div.c ./src/add.c ./src/subtract.c ./src/sub/mul.c ./src/sub/div.c ./src/add.c ./src/subtract.c ./src/sub/mul.c ./src/sub/div.c
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.