How to use `glob` module In Python

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. We will use glob.glob() function to achieve our task. The idea behind Unix shell-like means that we can provide Unix shell-like patterns for searching files.

Syntax:

 glob.glob(pathname, *, recursive=False)

Return a list of pathnames that match pathname, which must be a string containing a path specification.

The ‘*‘ means that it will match all the items returned by similar to os.listdir() method.

Example 1: Get all the directories and files in root/home/project/code

Python




import glob
 
list_ = glob.glob(r"root/home/project/code/*")
 
print(list_)


Output:

[‘database_models’, ‘README.md’, ‘requirements.txt’, ‘main.py’]

Example 2: Get all the python (.py) files in root/home/project/code/database_models

Python




import glob
 
list_ = glob.glob(r"root/home/project/code/database_models/*.py")
 
print(list_)


Output:

[‘schema_template.py’, ‘sqlalchemy_models.py’]



Python – List files in directory with extension

In this article, we will discuss different use cases where we want to list the files with their extensions present in a directory using python.

Similar Reads

Modules Used

os: The OS module in Python provides functions for interacting with the operating system. glob: 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....

Directory Structure in use:

...

Method 1: Using `os` module

This module provides a portable way of using operating system-dependent functionality. The method os.listdir() lists all the files present in a directory. We can make use of os.walk() if we want to work with sub-directories as well....

Method 2: Using `glob` module

...