The glob.glob gained the root_dir and dir_fd parameters in Python 3.10.

See Package description

You could do something like this :

def search_xlsx(rootdir):
    file_list = []
    for root, directories, file in os.walk(rootdir):
        for file in file:
            if(file.endswith(".xlsx")):
                file_list.append(file)
    return file_list
Answer from gcher495 on Stack Overflow
🌐
Python
docs.python.org › 3 › library › glob.html
glob — Unix style pathname pattern expansion — Python 3.15.2 documentation
If root_dir is not None, it should be a path-like object specifying the root directory for searching. It has the same effect on glob() as changing the current directory before calling it.
🌐
Note.nkmk.me
note.nkmk.me › home › python
How to Use glob() in Python | note.nkmk.me
July 28, 2023 - The root_dir argument in glob() can be utilized to specify the root directory.
Discussions

python 3.x - Error: glob() got an unexpected keyword argument 'root_dir' - Stack Overflow
The glob.glob gained the root_dir and dir_fd parameters in Python 3.10. More on stackoverflow.com
🌐 stackoverflow.com
python - How to use glob() to find files recursively? - Stack Overflow
In Python 3.9.1, recursive is set to False by default. 2020-12-30T21:53:35.673Z+00:00 ... Similar to other solutions, but using fnmatch.fnmatch instead of glob, since os.walk already listed the filenames: import os, fnmatch def find_files(directory, pattern): for root, dirs, files in ... More on stackoverflow.com
🌐 stackoverflow.com
linux - Python glob, os, relative path, making filenames into a list - Stack Overflow
I am trying to make a list of all files in a directory with filenames in a that end in .root. After reading some writings in the forum I tried to basic strategies using glob and os.listdir but I got into trouble for both of them More on stackoverflow.com
🌐 stackoverflow.com
Add the root_dir and dir_fd parameters in glob.glob()
🌐 github.com
September 12, 2019
🌐
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
If root_dir is not None, it should be a path-like object specifying the root directory for searching. It has the same effect on glob() as changing the current directory before calling it.
🌐
KM ENV TA BLOG
kaku-env.github.io › articles › 2024_02 › directory_analysis › 02_glob.html
Python - フォルダ構造を可視化しよう! 第2回:globモジュール - KM ENV TA BLOG
February 3, 2024 - glob.glob(r"C:\Program Files\Blender Foundation\Blender 3.6\*") # 以下と同義 glob.glob("*", root_dir=r"C:\Program Files\Blender Foundation\Blender 3.6") こちらも、バージョン3.5で追加された引数。デフォルト値はNone 。 公式ドキュメントの解説は、以下の通り。 · ディレクトリ記述子からの相対パス: dir_fd が None でない場合、その値はディレクトリを参照するファイル記述子である必要があり、また操作対象のファイルパスは相対パスである必要があります。 このときパスはファイル記述子が指すディレクトリからの相対パスと解釈されます。 パスが絶対パスの場合、 dir_fd は無視されます。
🌐
GitHub
github.com › python › cpython › blob › main › Lib › glob.py
cpython/Lib/glob.py at main · python/cpython · GitHub
`root_dir`. · If `dir_fd` is not None, it should be a file descriptor referring to a · directory, and paths will then be relative to that directory. · If `include_hidden` is true, wildcards can match path segments beginning · with a dot ('.'). · If `recursive` is true, the pattern '**' will match any files and · zero or more directories and subdirectories. """ sys.audit("glob.glob", pathname, recursive) sys.audit("glob.glob/2", pathname, recursive, root_dir, dir_fd) if root_dir is not None: root_dir = os.fspath(root_dir) else: root_dir = pathname[:0] it = _iglob(pathname, root_dir, dir_fd, recursive, False, include_hidden=include_hidden) if not pathname or recursive and _isrecursive(pathname[:2]): try: s = next(it) # skip empty string ·
🌐
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 - The glob function can be used to find just one folder or file. This can be done by just giving glob the path of the item you are trying to find. # Get a specific directory file_list = glob(data_folder) file_list
Find elsewhere
🌐
ZetCode
zetcode.com › python › glob
Python glob - File Pattern Matching
May 28, 2026 - The root_dir parameter does not change the process working directory; it only affects where the glob search begins. It can be combined with dir_fd (a file descriptor) when working with low-level OS interfaces.
Top answer
1 of 2
21

glob will return paths in a format matching your query, so that

glob.glob("/home/usr/dir/*.root")
# ['home/usr/dir/foo.root', 'home/usr/dir/bar.root', ...]

glob.glob("*.root")
# ['foo.root', 'bar.root', ...]

glob.glob("./*.root")
# ['./foo.root', './bar.root', ...]

...and so forth.

To get only the filename, you can use path.basename of the os module, something like this:

from glob import glob
from os import path

pattern = "/home/usr/dir/*.root"
files = [path.basename(x) for x in glob(pattern)]
# ['foo.root', 'bar.root', ...]

...or, if you want to prepend the dir part:

pattern = "/home/usr/dir/*.root"
files = [path.join('dir', path.basename(x)) for x in glob(pattern)]
# ['dir/foo.root', 'dir/bar.root', ...]

...or, if you really want the path separator at the start:

from glob import glob
import os

pattern = "/home/usr/dir/*.root"
files = [os.sep + os.path.join('dir', os.path.basename(x)) for x in glob(pattern)]
# ['/dir/foo.root', '/dir/bar.root', ...]

Using path.join and path.sep will make sure that the correct path syntax is used, depending on your OS (i.e. / or \ as a separator).

Depending on what you are really trying to do here, you might want to look at os.path.relpath, for the relative path. The title of your question indicates that relative paths might be what you are actually after:

pattern = "/home/usr/dir/*.root"
files = [os.path.relpath(x) for x in glob(pattern)]
# files will now contain the relative path to each file, from the current working directory
2 of 2
7

just use glob for getting the list you want
and then use os.path.relpath on each file

import glob
files_names = []
for file in glob.glob('/home/usr/dir/*.root'):
    files_names.append(os.path.relpath(file, "/home/usr"))

You can also use regex

import re
files_names.append(re.sub(r'//home//usr//','', file, flags=re.I))
🌐
Runebook.dev
runebook.dev › en › docs › python › library › pathlib › pathlib.Path.rglob
python - From os.walk to rglob(): The Modern Way to Search Directories
The behavior of globbing can be case-sensitive or case-insensitive depending on the operating system (OS). ... from pathlib import Path root_dir = Path("data") # Assuming a mix of .PNG and .png files # Search for all files, then filter by lowercased extension png_files_consistent = [ f for f in root_dir.rglob("*.*") if f.suffix.lower() == ".png" and f.is_file() ] print("\nPNG files (case-insensitive check):") for f in png_files_consistent: print(f)
🌐
GitHub
github.com › python › cpython › issues › 82325
Add the root_dir and dir_fd parameters in glob.glob() · Issue #82325 · python/cpython · GitHub
September 12, 2019 - If root_dir is absolute, dir_fd is ignored. If the pattern is absolute, root_dir and dir_fd are ignored. ... stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directory
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.

🌐
Stack Overflow
stackoverflow.com › questions › 66371422 › glob-doesnt-return-list-of-files-from-specified-directory
python - Glob doesn't return list of files from specified directory - Stack Overflow
In Python 3.10, you should be able to change the assumed root directory without using an absolute pattern via a new root_dir parameter, but this is not currently available in 3.9 and below: https://docs.python.org/3.10/library/glob.html.
🌐
Reddit
reddit.com › r/learnpython › glob module question
r/learnpython on Reddit: Glob Module Question
June 15, 2025 -

Hello,

Having issues working in VS Code (python 3.13.3) using "glob" to search for a list of .csv files in a folder. Not sure what set the error could be referring to, or how the module indexes (or doesn't I guess). Any help much appreciated.

Example code and terminal output down below:

import pandas as pd
import glob
import plotly.graph_objects as go

z_ref = 92.5
tol = 0.07
z_usl = z_ref * (1+tol)
z_lsl = z_ref * (1-tol)
folder = {f".\downloads*.csv"}
lst_csvs = glob.glob(folder)
print(lst_csvs)

> & C:/Users/Frameboiii/AppData/Local/Microsoft/WindowsApps/python3.13.exe c:/Users/Frameboiii/Downloads/random/script.py

c:\Users\Frameboiii\Downloads\random\script.py:9: SyntaxWarning: invalid escape sequence '\d'

folder = {f".\downloads*.csv"}

Traceback (most recent call last):

File "c:\Users\Frameboiii\Downloads\random\script.py", line 10, in <module>

lst_csvs = glob.glob(folder)

File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.13_3.13.1008.0_x64__qbz5n2kfra8p0\Lib\glob.py", line 31, in glob

return list(iglob(pathname, root_dir=root_dir, dir_fd=dir_fd, recursive=recursive,

include_hidden=include_hidden))

File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.13_3.13.1008.0_x64__qbz5n2kfra8p0\Lib\glob.py", line 51, in iglob

root_dir = pathname[:0]

TypeError: 'set' object is not subscriptable

🌐
GitHub
github.com › python › cpython › issues › 116320
`glob.glob("**", root_dir=root, recursive=True)` doesn't return root · Issue #116320 · python/cpython · GitHub
March 4, 2024 - >>> import glob >>> glob.glob('my_dir/**', recursive=True) ['my_dir/', 'my_dir/my_file'] >>> glob.glob('**', root_dir='my_dir/', recursive=True) ['my_file'] # should include './'
🌐
Python
bugs.python.org › issue38144
Issue 38144: Add the root_dir and dir_fd parameters in glob.glob() - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/82325
🌐
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