In Python 3.5 and newer use the new recursive **/ functionality:

configfiles = glob.glob('C:/Users/sam/Desktop/file1/**/*.txt', recursive=True)

When recursive is set, ** followed by a path separator matches 0 or more subdirectories.

In earlier Python versions, glob.glob() cannot list files in subdirectories recursively.

In that case I'd use os.walk() combined with fnmatch.filter() instead:

import os
import fnmatch

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in fnmatch.filter(files, '*.txt')]

This'll walk your directories recursively and return all absolute pathnames to matching .txt files. In this specific case the fnmatch.filter() may be overkill, you could also use a .endswith() test:

import os

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in files if f.endswith('.txt')]
Answer from Martijn Pieters on Stack Overflow
Top answer
1 of 13
258

In Python 3.5 and newer use the new recursive **/ functionality:

configfiles = glob.glob('C:/Users/sam/Desktop/file1/**/*.txt', recursive=True)

When recursive is set, ** followed by a path separator matches 0 or more subdirectories.

In earlier Python versions, glob.glob() cannot list files in subdirectories recursively.

In that case I'd use os.walk() combined with fnmatch.filter() instead:

import os
import fnmatch

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in fnmatch.filter(files, '*.txt')]

This'll walk your directories recursively and return all absolute pathnames to matching .txt files. In this specific case the fnmatch.filter() may be overkill, you could also use a .endswith() test:

import os

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in files if f.endswith('.txt')]
2 of 13
93

There's a lot of confusion on this topic. Let me see if I can clarify it (Python 3.7):

  1. glob.glob('*.txt') :matches all files ending in '.txt' in current directory
  2. glob.glob('*/*.txt') :same as 1
  3. glob.glob('**/*.txt') :matches all files ending in '.txt' in the immediate subdirectories only, but not in the current directory
  4. glob.glob('*.txt',recursive=True) :same as 1
  5. glob.glob('*/*.txt',recursive=True) :same as 3
  6. glob.glob('**/*.txt',recursive=True):matches all files ending in '.txt' in the current directory and in all subdirectories

So it's best to always specify recursive=True.

๐ŸŒ
Medium
karliris62.medium.com โ€บ how-to-use-glob-function-to-find-files-recursively-in-python-b746af8afbc2
How to use Glob() function to find files recursively in Python? | by Gaurav Roy CTO, Masters | BS-Cyber-Sec | MIT | LPU | Medium
August 18, 2022 - Then we have to use the glob() method where we will pass the path that will look for all the subdirectories and print it using the print() function. Next, we will use different patterns such as * (asterisk), ? (wildcard), and [range] to the ...
People also ask

What Python version introduced recursive searching with glob?
A: Recursive searching with the ** wildcard was introduced in Python 3.5. Make sure you are using a compatible version for this functionality.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ solved-top-methods-for-searching-subfolders-with-glob
Solved: Top Methods for Searching Subfolders with the Glob Module ...
How does the glob module work for searching files?
A: The glob module allows you to match file paths using Unix shell-style wildcards, helping you efficiently search files by patterns or names.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ solved-top-methods-for-searching-subfolders-with-glob
Solved: Top Methods for Searching Subfolders with the Glob Module ...
Is pathlib preferable over glob?
A: While both libraries are effective, pathlib provides an object-oriented approach and offers additional functionalities that may be easier to work with.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ solved-top-methods-for-searching-subfolders-with-glob
Solved: Top Methods for Searching Subfolders with the Glob Module ...
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python list subdirectories
How to List Subdirectories in Python | Delft Stack
February 2, 2024 - There are three effective methods that you can use to list all the subdirectories inside a specified directory in Python: the glob.glob() function, the os.scandir() function, and the os.walk() function.
๐ŸŒ
My Website
reimaginebelonging.de โ€บ home โ€บ glob find all files in subfolders
Glob Find All Files In Subfolders
June 2, 2026 - When you need to glob find all files in subfolders scattered across a deeply nested directory tree, Pythonโ€™s built-in glob module delivers a clean, pattern-based approach that eliminates tedious manual path building. Instead of writing nested loops to visit every folder level, you can use wildcard expressions to describe the files you want, then let the library traverse the entire structure for you.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-use-glob-function-to-find-files-recursively-in-python
How to use Glob() Function to Find Files Recursively in Python - GeeksforGeeks
October 3, 2025 - Both glob.glob() (returns a list) and glob.iglob() (returns an iterator) support recursion. ... # 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)
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ glob.html
glob โ€” Unix style pathname pattern expansion โ€” Python 3.15.2 documentation
The glob module finds pathnames using pattern matching rules similar to the Unix shell. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.
๐ŸŒ
sqlpey
sqlpey.com โ€บ python โ€บ solved-top-methods-for-searching-subfolders-with-glob
Solved: Top Methods for Searching Subfolders with the Glob Module in Python
November 6, 2024 - However, this will not fetch files located in subfolders. To include them, here is how to specify the search pattern. If you only want to find text files in immediate subdirectories, use: config_files = glob.glob(r'C:\Users\sam\Desktop\*\*.txt') For a full recursive search that includes all subdirectories, you can take advantage of the ** wildcard introduced in Python 3.5:
Find elsewhere
๐ŸŒ
pythontutorials
pythontutorials.net โ€บ blog โ€บ how-can-i-search-sub-folders-using-glob-glob-module
How to Recursively Search Subfolders for Files Using glob.glob in Python โ€” pythontutorials.net
Recursively searching subfolders with glob.glob is a powerful technique for file management in Python. By combining the ** wildcard with recursive=True, you can easily traverse nested directories and match complex file patterns.
๐ŸŒ
Iditect
iditect.com โ€บ faq โ€บ python โ€บ how-to-search-subfolders-using-globglob-module.html
How to search sub-folders using glob.glob module?
You can search for files in sub-folders using the glob.glob module in Python by specifying a wildcard pattern that includes the sub-folder(s) you want to search. The ** syntax can be used to represent multiple levels of sub-folders.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-list-all-files-in-directory-and-subdirectories
Python List All Files In Directory And Subdirectories - GeeksforGeeks
July 23, 2025 - In this example, the Python function `list_files_glob` uses the `glob` module to list and print the full paths of files matching a specified pattern (`'./**/*'` by default). The `recursive` parameter is set to `True` by default, allowing it to recursively search subdirectories.
๐ŸŒ
Medium
medium.com โ€บ codex โ€บ using-python-to-get-a-list-of-files-in-a-folder-or-sub-folders-part-1-a76468dbe06
Using Python to list files in a folder or sub-folder (part 1) | by Sid Ghani | CodeX | Medium
September 14, 2022 - The advantage Glob has is that it uses fewer lines of code and you can search for specific files which contain specific strings. Let's take an example, I have the folder below which contains a mixture of files, I need a list of all .mp4 files which are a type of video file and I need to find all .mp4 files which sit within any subfolders. My folder contains a mix of file types and subfolders
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ glob
glob โ€“ Filename pattern matching - Python Module of the Week
import glob for name in glob.glob('dir/*'): print name ยท The pattern matches every pathname (file or directory) in the directory dir, without recursing further into subdirectories. $ python glob_asterisk.py dir/file.txt dir/file1.txt dir/file2.txt dir/filea.txt dir/fileb.txt dir/subdir
๐ŸŒ
YouTube
youtube.com โ€บ watch
Read files in a folder and subfolders| glob module python | read multiple csv| read multiple jpg,etc - YouTube
This video explains about how to read multiple files from a folder and subfolders using python glob module. In data science projects sometimes we have to dea...
Published: April 29, 2022
Top answer
1 of 16
969

Do you mean immediate subdirectories, or every directory right down the tree?

Either way, you could use os.walk to do this:

os.walk(directory)

will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so

[x[0] for x in os.walk(directory)]

should give you all of the subdirectories, recursively.

Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it's not likely to save you much.

However, you could use it just to give you the immediate child directories:

next(os.walk('.'))[1]

Or see the other solutions already posted, using os.listdir and os.path.isdir, including those at "How to get all of the immediate subdirectories in Python".

2 of 16
358

Much nicer than the above, because you don't need several os.path.join() and you will get the full path directly (if you wish), you can do this in Python 3.5 and above.

subfolders = [ f.path for f in os.scandir(folder) if f.is_dir() ]

This will give the complete path to the subdirectory. If you only want the name of the subdirectory use f.name instead of f.path

https://docs.python.org/3/library/os.html#os.scandir


Slightly OT: In case you need all subfolder recursively and/or all files recursively, have a look at this function, that is faster than os.walk & glob and will return a list of all subfolders as well as all files inside those (sub-)subfolders: https://stackoverflow.com/a/59803793/2441026

In case you want only all subfolders recursively:

def fast_scandir(dirname):
    subfolders= [f.path for f in os.scandir(dirname) if f.is_dir()]
    for dirname in list(subfolders):
        subfolders.extend(fast_scandir(dirname))
    return subfolders

Returns a list of all subfolders with their full paths. This again is faster than os.walk and a lot faster than glob.


An analysis of all functions

tl;dr:
- If you want to get all immediate subdirectories for a folder use os.scandir.
- If you want to get all subdirectories, even nested ones, use os.walk or - slightly faster - the fast_scandir function above.
- Never use os.walk for only top-level subdirectories, as it can be hundreds(!) of times slower than os.scandir.

  • If you run the code below, make sure to run it once so that your OS will have accessed the folder, discard the results and run the test, otherwise results will be screwed.
  • You might want to mix up the function calls, but I tested it, and it did not really matter.
  • All examples will give the full path to the folder. The pathlib example as a (Windows)Path object.
  • The first element of os.walk will be the base folder. So you will not get only subdirectories. You can use fu.pop(0) to remove it.
  • None of the results will use natural sorting. This means results will be sorted like this: 1, 10, 2. To get natural sorting (1, 2, 10), please have a look at https://stackoverflow.com/a/48030307/2441026


Results:

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439

Tested with W7x64, Python 3.8.1.

# -*- coding: utf-8 -*-
# Python 3


import time
import os
from glob import glob
from pathlib import Path


directory = r"<insert_folder>"
RUNS = 1


def run_os_walk():
    a = time.time_ns()
    for i in range(RUNS):
        fu = [x[0] for x in os.walk(directory)]
    print(f"os.walk\t\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_glob():
    a = time.time_ns()
    for i in range(RUNS):
        fu = glob(directory + "/*/")
    print(f"glob.glob\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_pathlib_iterdir():
    a = time.time_ns()
    for i in range(RUNS):
        dirname = Path(directory)
        fu = [f for f in dirname.iterdir() if f.is_dir()]
    print(f"pathlib.iterdir\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_os_listdir():
    a = time.time_ns()
    for i in range(RUNS):
        dirname = Path(directory)
        fu = [os.path.join(directory, o) for o in os.listdir(directory) if os.path.isdir(os.path.join(directory, o))]
    print(f"os.listdir\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_os_scandir():
    a = time.time_ns()
    for i in range(RUNS):
        fu = [f.path for f in os.scandir(directory) if f.is_dir()]
    print(f"os.scandir\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len(fu)}")


if __name__ == '__main__':
    run_os_scandir()
    run_os_walk()
    run_glob()
    run_pathlib_iterdir()
    run_os_listdir()
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
How to Use glob() in Python | note.nkmk.me
July 28, 2023 - In Python, the glob module allows you to get a list or an iterator of file and directory paths that satisfy certain conditions using special characters like the wildcard *. glob โ€” Unix style pathname ...
๐ŸŒ
Techie Delight
techiedelight.com โ€บ home โ€บ python โ€บ list all subdirectories in a directory in python
List all subdirectories in a directory in Python | Techie Delight
July 7, 2026 - Finally, you can use the glob.glob function, which returns an iterator over the list of pathnames that match the specified pattern. ... Python 3.5 extended support for recursive globs using ** to search subdirectories and symbolic links to directories.