The Wayback Machine - https://web.archive.org/web/20241126231552/https://www.geeksforgeeks.org/how-to-use-glob-function-to-find-files-recursively-in-python/
Open In App

How to use Glob() function to find files recursively in Python?

Last Updated : 02 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Example:

Python3 1==
# Python program to demonstrate
# glob using different wildcards


import glob


print('Named explicitly:')
for name in glob.glob('/home/geeks/Desktop/gfg/data.txt'):
    print(name)

# Using '*' pattern 
print('\nNamed with wildcard *:')
for name in glob.glob('/home/geeks/Desktop/gfg/*'):
    print(name)

# Using '?' pattern
print('\nNamed with wildcard ?:')
for name in glob.glob('/home/geeks/Desktop/gfg/data?.txt'):
    print(name)

# Using [0-9] pattern
print('\nNamed with wildcard ranges:')
for name in glob.glob('/home/geeks/Desktop/gfg/*[0-9].*'):
    print(name)

Output :

python-glob

Using Glob() function to find files recursively

We can use the function

glob.glob()

or

glob.iglob()

directly from glob module to retrieve paths recursively from inside the directories/files and subdirectories/subfiles.

Syntax:

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

Note:

When recursive is set

True

“

**

” followed by path separator

('./**/')

will match any files or directories.

Example:

Python3 1==
# 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 :

python-glob

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-

Example:

Python3 1==
# Python program to find files
# recursively using Python


import os
 
# Using os.walk()
for dirpath, dirs, files in os.walk('src'): 
  for filename in files:
    fname = os.path.join(dirpath,filename)
    if fname.endswith('.c'):
      print(fname)
 
"""
Or
We can also use fnmatch.filter()
to filter out results.
"""
for dirpath, dirs, files in os.walk('src'): 
  for filename in fnmatch.filter(files, '*.c'):
    print(os.path.join(dirpath, filename))
 
# Using os.listdir()
path = "src"
dir_list = os.listdir(path)
for filename in fnmatch.filter(dir_list,'*.c'):
  print(os.path.join(dirpath, filename))

Output :

 
./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

How to use Glob() function to find files recursively in Python? – FAQs

How do I find files recursively in Python glob?

To find files recursively using the glob module in Python, you can use the ** pattern in combination with the glob() method, setting the recursive parameter to True. This allows the pattern to match directories and subdirectories.

Example:

import glob

# Find all .txt files in the current directory and subdirectories
files = glob.glob('**/*.txt', recursive=True)
print(files)

This will list all .txt files in the current directory and all subdirectories.

How to List Files Recursively in Python?

Listing files recursively can also be done using the os module if you need more control over the traversal process:

Example:

import os

# List all files in a directory recursively
for root, dirs, files in os.walk('.'):
for file in files:
print(os.path.join(root, file))

This uses os.walk() to navigate through all directories and subdirectories, printing paths of all files.

Why is my glob not working recursively?

If your glob.glob() is not working recursively, ensure:

  1. Python Version: Make sure you are using Python 3.5 or newer, as recursive globbing was added in Python 3.5.
  2. Recursive Flag: Check that the recursive=True parameter is set in your glob() call.
  3. Pattern: Ensure that your pattern includes the ** to match directories recursively.

Example:

files = glob.glob('**/*.txt', recursive=True)  # Correct usage

How do I find files matching glob in Python?

To find files matching a specific pattern using glob, you simply specify the pattern as an argument to glob.glob().

Example:

import glob

# Find all JPEG files in the current directory
jpeg_files = glob.glob('*.jpg')
print(jpeg_files)

Which command is used to recursively copy the files?

In Python, to recursively copy files, you can use the shutil module which provides a utility function copytree() to copy an entire directory tree.

Example:

import shutil

# Recursively copy an entire directory tree
source_dir = 'path/to/source_directory'
destination_dir = 'path/to/destination_directory'
shutil.copytree(source_dir, destination_dir)

This command will copy all the contents of source_dir to a new location destination_dir including all subdirectories and files.



Previous Article
Next Article

Similar Reads

glob – Filename pattern matching
Glob module searches all path names looking for files matching a specified pattern according to the rules dictated by the Unix shell. Results so obtained are returned in arbitrary order. Some requirements need traversal through a list of files at some location, mostly having a specific pattern. Python’s glob module has several functions that can he
3 min read
How to merge multiple excel files into a single files with Python ?
Normally, we're working with Excel files, and we surely have come across a scenario where we need to merge multiple Excel files into one. The traditional method has always been using a VBA code inside excel which does the job but is a multi-step process and is not so easy to understand. Another method is manually copying long Excel files into one w
4 min read
Copy a directory recursively using Python (with examples)
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the desti
5 min read
Python | How to use Multiple kv files in kivy
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. In this article, we will see how can we use multiple .kv files in a single Application . This is the Python progra
3 min read
How To Use Python To Parse Server Log Files
Server log files are an invaluable source of information for system administrators and developers. They contain records of various events and activities that occur on a server, such as requests, errors, warnings, and more. Parsing these log files can provide insights into system performance, security issues, and user behavior. What is Parsing Serve
4 min read
Python | Create Archives and Find Files by Name
In this article, we will learn how to create or unpack archives in common formats (e.g., .tar, .tgz, or .zip) using shutil module. The shutil module has two functions — make_archive() and unpack_archive() — that can exactly be the solution. Code #1 : import shutil shutil.unpack_archive('Python-3.3.0.tgz') shutil.make_archive('py33', 'zip', 'Python-
3 min read
Find all the Files in a Directory with .txt Extension in Python
Directory traversal is a common operation performed by file locator in Operating Systems. The operating system offers elaborate methods for streamlining the search process and the choice to search for a selected filename/extension. This article will teach you how to find all the files in a directory with a .txt (text files) extension using Python.
5 min read
Use of nonlocal vs use of global keyword in Python
Prerequisites: Global and Local Variables in PythonBefore moving to nonlocal and global in Python. Let us consider some basic scenarios in nested functions. C/C++ Code def fun(): var1 = 10 def gun(): print(var1) var2 = var1 + 1 print(var2) gun() fun() Output: 10 11 The variable var1 has scope across entire fun(). It will be accessible from nested f
3 min read
Upload and Download files from Google Drive storage using Python
In this article, we are going to see how can we download files from our Google Drive to our PC and upload files from our PC to Google Drive using its API in Python. It is a REST API that allows you to leverage Google Drive storage from within your app or program. So, let's go ahead and write a Python script to do that. Requirements: Python (2.6 or
6 min read
Python | Write multiple files data to master file
Given a number of input files in a source directory, write a Python program to read data from all the files and write it to a single master file. Source directory contains n number of files, and structure is same for all files. The objective of this code is to read all the files one by one and then append the output into a single master file having
2 min read
How to create a list of files, folders, and subfolders in Excel using Python ?
In this article, we will learn How to create a list of Files, Folders, and Sub Folders and then export them to Excel using Python. We will create a list of names and paths using a few folder traversing methods explained below and store them in an Excel sheet by either using openpyxl or pandas module. Input: The following image represents the struct
12 min read
Upload files in Python
In this article, we will be looking into the process of file uploading in Python using cgi environment. One often comes across various web applications in which the client or the users is required to upload data in the form of a file(eg. image file, an audio file, text file, etc). There are two aspects to uploading a file, as there are two sides to
3 min read
Python | Reading .ini Configuration Files
This article aims to read configuration files written in the common .ini configuration file format. The configparser module can be used to read configuration files. Code #1 : Configuration File abc.ini ; Sample configuration file [installation] library = %(prefix)s/lib include = %(prefix)s/include bin = %(prefix)s/bin prefix = /usr/local # Setting
3 min read
Python | Move or Copy Files and Directories
Let's say we want to copy or move files and directories around, but don’t want to do it by calling out to shell commands. The shutil module has portable implementations of functions for copying files and directories. Code #1 : Using shutil module import shutil # Copy src to dst. (cp src dst) shutil.copy(src, dst) # Copy files, but preserve metadata
3 min read
How to move all files from one directory to another using Python ?
In this article, we will see how to move all files from one directory to another directory using Python. In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil module.Source and Destination Folder Setup Before Ru
2 min read
How to move Files and Directories in Python
Python provides functionality to move files or directories from one location to another location. This can be achieved using shutil.move() function from shutil module. shutil.move() method Recursively moves a file or directory (source) to another location (destination) and returns the destination. If the destination directory already exists then sr
2 min read
Check if directory contains files using python
Finding if a directory is empty or not in Python can be achieved using the listdir() method of the os library. OS module in Python provides functions for interacting with the operating system. This module provides a portable way of using operating system dependent functionality. Syntax: os.listdir(<directory path>) Returns: A list of files pr
3 min read
Interact with files in Python
Python too supports file handling and allows users to handle files i.e., to read, write, create, delete and move files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python
6 min read
HDF5 files in Python
HDF5 file stands for Hierarchical Data Format 5. It is an open-source file which comes in handy to store large amount of data. As the name suggests, it stores data in a hierarchical structure within a single file. So if we want to quickly access a particular part of the file rather than the whole file, we can easily do that using HDF5. This functio
5 min read
Python - Add audio files in kivy
Kivy is a platform independent GUI tool in Python. Kivy is a tool used to build cross-platform applications in Python which can run on android, IOS, Linux, Windows. Audio Widget: This module is used to load audio files in kivy. from kivy.core.audio import SoundLoader Below is the code on how you can import an audio file in kivy. NOTE:You can import
1 min read
Uploading files on Google Drive using Python
In the modern era of the internet, a large number of mundane or work-related tasks are carried out over the internet. Compromise of data stored on a device could cause massive harm to an individual/company. Considering the rise in the number of malware, viruses, worms, trojan horse etc the security of data at rest has become a concern for many peop
3 min read
Python - Move all files from subfolders to main folder
This article will discuss how to move all files from the subfolder to the main folder using Python. The approach is simple it is similar to moving files from one folder to another using Python, except here the main folder or parent folder of the subfolder is passed as the destination. Modules UsedOS Module: OS module in Python provides functions to
3 min read
Compare two files using Hashing in Python
In this article, we would be creating a program that would determine, whether the two files provided to it are the same or not. By the same means that their contents are the same or not (excluding any metadata). We would be using Cryptographic Hashes for this purpose. A cryptographic hash function is a function that takes in input data and produces
3 min read
Read and Write TOML Files Using Python
TOML file stand for (Tom's Obvious, Minimum Language). The configuration files can be stored in TOML files, which have the .toml extension. Due to its straightforward semantics, which strives to be "minimal," it is supposed to be simple to read and write. It is also made to clearly map to a dictionary. The TOML's syntax primarily consists of key =
6 min read
Modify XML files with Python
Python|Modifying/Parsing XML Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.The design goals of XML focus on simplicity, generality, and usability across the Internet.It is a textual data format with strong support via Unicode for
4 min read
Reading and Writing CSV Files in Python
CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. It is one of the most common methods for exchanging data between applications and popular data format used in Data Science. It is supported by a wide range of applications. A CSV file stores tabular data in which each data field is separa
4 min read
How to Scrape Data From Local HTML Files using Python?
BeautifulSoup module in Python allows us to scrape data from local HTML files. For some reason, website pages might get stored in a local (offline environment), and whenever in need, there may be requirements to get the data from them. Sometimes there may be a need to get data from multiple Locally stored HTML files too. Usually HTML files got the
4 min read
How to Delete files in Python using send2trash module?
In this article, we will see how to safely delete files and folders using the send2trash module in Python. Using send2trash, we can send files to the Trash or Recycle Bin instead of permanently deleting them. The OS module's unlink(), remove() and rmdir() functions can be used to delete files or folders. But, these functions delete the files perman
2 min read
Python - Move and overwrite files and folders
In this article, we will be learning on moving a collection of files and folders where there may be files/folders with the same name as in the source name in the destination. So that we may need to overwrite the existing destination file with the source file. The shutil.move() method is used to move a file or directory from one place to another. If
3 min read
Joining Excel Data from Multiple files using Python Pandas
Let us see how to join the data of two excel files and save the merged data as a new Excel file. We have 2 files, registration details.xlsx and exam results.xlsx. registration details.xlsx We are having 7 columns in this file with 14 unique students details. Column names are as follows : Admission Date Name of Student Gender DOB Student email Id En
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg