1. what is glob and, what it used for

The glob module finds all the pathnames matching a specified pattern. for example, if you want to find a file pathname ends with ".py" or you want to search a file in multi-folder so let's start with examples for More clarity.


1. Searching for files which end with .txt on a single folder

but first, let's see what we have in our folder

command :

 
    glob.glob('/home/py/Desktop/glob/*')

"*" means get all things in the folder

output:

 
#  ['/home/py/Desktop/glob/image.jpg', '/home/py/Desktop/glob/test2.txt', '/home/py/Desktop/glob/image-1.jpg', '/home/py/Desktop/glob/test.txt', '/home/py/Desktop/glob/video.mp4', '/home/py/Desktop/glob/image-3.jpg', '/home/py/Desktop/glob/image-2.mp4']

as you can see we have many file in the folder but now we need to get just files which are end with ".txt"

command :

 
# glob.glob('/home/py/Desktop/glob/*.txt')

output:

 
# ['/home/py/Desktop/glob/test2.txt', '/home/py/Desktop/glob/test.txt']


2. Searching for files which end with .txt on multi folder

imagine we have a folder this folder contains many folders and we want to search for something on all these folders, of course, the code above Will not work
but we can do that by the code below

code:

 glob.glob('/home/py/Desktop/glob/**/*.txt', recursive=True)

If recursive is true, the pattern “**” will match any files and zero or more directories and subdirectories. If the pattern is followed by an os.sep, only directories and subdirectories match.

output:

 
# ['/home/py/Desktop/glob/test2.txt', '/home/py/Desktop/glob/test.txt', '/home/py/Desktop/glob/folder2/testfolder.txt']

thanks

English today is not an art to be mastered it's just a tool to use to get a result