Glob Module in Python-Explained

H. Ali
2 min readApr 20, 2022

--

a man holding bunch of files and looking for specific files.
glob module in Python Gives you ease to search files using patterns.

What is Glob Module in Python?

In Python, the glob module is a way of searching files pathnames using a specified pattern.

Python glob module makes it easy to find all pathnames that match a specific pattern.

Well, you can do a very much similar task using regular expression in python. Then why need glob module for searching file names?

well, most of the time there is more than one way to do a job. Though we can have more control over regular expressions for finding a pattern. The glob module in python is a Unix style of searching pathnames.

How to Install Python glob module?

glob module comes with the python programming language. It means you need not install it manually, but sometimes maybe you face some problems.

So here is the answer for installation. you can use pip to install glob module. Remember, you have to install glob2 not glob.

glob and glob2 are the same things but during installation, you have to refer to glob2.

pip install glob2

How to Import Python Glob module?

Though you have installed it using glob2 as a name, you have to import it using the name glob, not glob2.

import glob

Search for all python files in a Directory using glob module

In this example, let's say, we have a bunch of directories and files. We need to search for python files in all directories and subdirectories.

Look at the following Screenshot where you will see all files and directories.

screenshot of python project. where there are multiple files, most of them are .py files.
screenshot of my final year project

Python glob module has glob() function, which can help us look for all python files recursively.

Check the following python code. Where it help us find all .py files in all subdirectories, recursively.

Word From My Heart

Thank you so much for coming this far. Please make sure you leave a like and let me know if you have any questions. I would love to hear from you.

--

--

H. Ali
H. Ali

Written by H. Ali

Software Engineer | Content Creator

Responses (2)