Maybe there is a better way, but how about:

import glob
types = ('*.pdf', '*.cpp') # the tuple of file types
files_grabbed = []
for files in types:
    files_grabbed.extend(glob.glob(files))

# files_grabbed is the list of pdf and cpp files

Perhaps there is another way, so wait in case someone else comes up with a better answer.

Answer from user225312 on Stack Overflow
🌐
Python
docs.python.org › 3 › library › glob.html
glob — Unix style pathname pattern expansion
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.
🌐
W3Schools
w3schools.com › python › ref_module_glob.asp
Python glob Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... import glob import tempfile import os with tempfile.TemporaryDirectory() as d: open(os.path.join(d, "Emil.txt"), "w").close() open(os.path.join(d, "Linus.txt"), "w").close() open(os.path.join(d, "Tobias.py"), "w").close() hits = glob.glob(os.path.join(d, "*.txt")) print(sorted(os.path.basename(x) for x in hits)) Try it Yourself »
🌐
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 - Glob is a powerful pattern-matching technique widely used in Unix and Linux environments for matching file and directory names based on wildcard patterns. Python’s built-in glob module provides similar functionality, enabling you to easily ...
🌐
Built In
builtin.com › software-engineering-perspectives › glob-in-python
Glob in Python Explained | Built In
Glob is a Python module that’s used to search for file path names that match a specific pattern.
🌐
Real Python
realpython.com › ref › stdlib › glob
glob | Python Standard Library – Real Python
The Python glob module provides tools to find path names matching specified patterns that follow Unix shell rules.
Find elsewhere
🌐
YouTube
youtube.com › watch
Python Pathlib Glob Tutorial | Replace Glob Module with Pathlib - YouTube
SEO Description:Learn how to replace Python’s traditional glob module with the modern pathlib library. In this tutorial, we’ll explore how Path.glob() makes ...
Published: August 28, 2025
🌐
Georgefox
cs.georgefox.edu › hs_contest › docs › python-3.10.12-docs › library › glob.html
glob — Unix style pathname pattern expansion — Python 3.10.12 documentation
The Python Standard Library » · File and Directory Access » · glob — Unix style pathname pattern expansion · | Theme · Auto · Light · Dark | Source code: Lib/glob.py · The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, ...
🌐
YouTube
youtube.com › watch
Python and the Glob Function Easy Tutorial
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
GitHub
github.com › python › cpython › blob › main › Lib › glob.py
cpython/Lib/glob.py at main · python/cpython
"""Filename globbing utility.""" · import contextlib · import os · import re · import fnmatch · import functools · import itertools · import operator · import stat · import sys · · · __all__ = ["glob", "iglob", "escape", "translate"] · def glob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False): """Return a list of paths matching a `pathname` pattern.
🌐
ChristopherGS
christophergs.com › python › 2017 › 01 › 01 › python-glob
Using Python glob
January 1, 2017 - fnmatch: glob uses fnmatch.fnmatch under the hood. For recursive file selection in older versions of Python, see this discussion.
🌐
Medium
medium.com › @sampathbasa › python-glob-simplifying-file-management-d09ec1c04340
Python Glob: Simplifying File Management | by Sampathkumarbasa | Medium
November 16, 2023 - Python Glob is a module that helps you search for files using pattern matching. It’s incredibly versatile and user-friendly.
🌐
Earth Data Science
earthdatascience.org › home
Use the OS and Glob Python Packages to Manipulate File Paths | Earth Data Science - Earth Lab
November 12, 2020 - glob is a powerful tool in Python to help with file management and filtering.
🌐
Medium
medium.com › django-unleashed › python-file-handling-with-the-glob-module-a-comprehensive-guide-10b209fcbfbb
Python File Handling with the glob Module: A Comprehensive Guide | by Mehedi Khan | Django Unleashed | Medium
February 15, 2025 - In Python, handling files and ... application. The glob module in Python is a powerful tool that simplifies the process of finding files that match a specific pattern in a directory....
🌐
arXiv
arxiv.org › html › 2509.08843v1
Pattern-Based File and Data Access with Python Glob: A Comprehensive Guide for Computational Research
September 4, 2025 - Pattern-based file access is a fundamental but often under-documented aspect of computational research. The Python glob module provides a simple yet powerful way to search, filter, and ingest files using wildcard patterns, enabling scalable workflows across disciplines.
🌐
Read the Docs
python.readthedocs.io › fr › latest › library › glob.html
11.7. glob — Unix style pathname pattern expansion — documentation Python 3.7.0a0
The Python Standard Library » · 11. File and Directory Access » · | Source code: Lib/glob.py · The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order.
Top answer
1 of 12
64

The glob module uses the fnmatch module for individual path elements.

That means the path is split into the directory name and the filename, and if the directory name contains meta characters (contains any of the characters [, * or ?) then these are expanded recursively.

If you have a list of strings that are simple filenames, then just using the fnmatch.filter() function is enough:

import fnmatch

matching = fnmatch.filter(filenames, pattern)

but if they contain full paths, you need to do more work as the regular expression generated doesn't take path segments into account (wildcards don't exclude the separators nor are they adjusted for cross-platform path matching).

You can construct a simple trie from the paths, then match your pattern against that:

import fnmatch
import glob
import os.path
from itertools import product


# Cross-Python dictionary views on the keys 
if hasattr(dict, 'viewkeys'):
    # Python 2
    def _viewkeys(d):
        return d.viewkeys()
else:
    # Python 3
    def _viewkeys(d):
        return d.keys()


def _in_trie(trie, path):
    """Determine if path is completely in trie"""
    current = trie
    for elem in path:
        try:
            current = current[elem]
        except KeyError:
            return False
    return None in current


def find_matching_paths(paths, pattern):
    """Produce a list of paths that match the pattern.

    * paths is a list of strings representing filesystem paths
    * pattern is a glob pattern as supported by the fnmatch module

    """
    if os.altsep:  # normalise
        pattern = pattern.replace(os.altsep, os.sep)
    pattern = pattern.split(os.sep)

    # build a trie out of path elements; efficiently search on prefixes
    path_trie = {}
    for path in paths:
        if os.altsep:  # normalise
            path = path.replace(os.altsep, os.sep)
        _, path = os.path.splitdrive(path)
        elems = path.split(os.sep)
        current = path_trie
        for elem in elems:
            current = current.setdefault(elem, {})
        current.setdefault(None, None)  # sentinel

    matching = []

    current_level = [path_trie]
    for subpattern in pattern:
        if not glob.has_magic(subpattern):
            # plain element, element must be in the trie or there are
            # 0 matches
            if not any(subpattern in d for d in current_level):
                return []
            matching.append([subpattern])
            current_level = [d[subpattern] for d in current_level if subpattern in d]
        else:
            # match all next levels in the trie that match the pattern
            matched_names = fnmatch.filter({k for d in current_level for k in d}, subpattern)
            if not matched_names:
                # nothing found
                return []
            matching.append(matched_names)
            current_level = [d[n] for d in current_level for n in _viewkeys(d) & set(matched_names)]

    return [os.sep.join(p) for p in product(*matching)
            if _in_trie(path_trie, p)]

This mouthful can quickly find matches using globs anywhere along the path:

>>> paths = ['/foo/bar/baz', '/spam/eggs/baz', '/foo/bar/bar']
>>> find_matching_paths(paths, '/foo/bar/*')
['/foo/bar/baz', '/foo/bar/bar']
>>> find_matching_paths(paths, '/*/bar/b*')
['/foo/bar/baz', '/foo/bar/bar']
>>> find_matching_paths(paths, '/*/[be]*/b*')
['/foo/bar/baz', '/foo/bar/bar', '/spam/eggs/baz']
2 of 12
39

On Python 3.4+ you can just use PurePath.match.

pathlib.PurePath(path_string).match(pattern)

On Python 3.3 or earlier (including 2.x), get pathlib from PyPI.

Note that to get platform-independent results (which will depend on why you're running this) you'd want to explicitly state PurePosixPath or PureWindowsPath.