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
Answer from leo on Stack Overflow
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))
🌐
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 ... as changing the current directory before calling it. If pathname is relative, the result will contain paths relative to root_dir....
🌐
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 - With this information, you can set the working directory to your earth-analytics directory and then create a relative path to the downloaded data directory. # Set working directory to earth-analytics os.chdir(os.path.join(et.io.HOME, "earth-analytics")) # Create a path to the data folder data_folder = os.path.join("data", "earthpy-downloads", "avg-monthly-temp-fahr") glob is a powerful tool in Python to help with file management and filtering.
🌐
Roadmap
roadmap.sh › python › glob
Python glob Module: File Pattern Matching Explained
March 3, 2026 - Setting recursive=True tells glob to walk through the entire directory tree under the specified path. Note that when dealing with directories with thousands of files, recursive searches can take longer to scan and can affect performance. ... Generate glob examples to practice recursive and non-recursive searches. One useful feature of glob is its support for both relative and absolute paths.
🌐
PYnative
pynative.com › home › python › python glob: filename pattern matching
Python Glob: Filename Pattern Matching – PYnative
June 17, 2021 - import glob # relative path to search all text files files = glob.glob("*.txt") print(files)Code language: Python (python)
🌐
Note.nkmk.me
note.nkmk.me › home › python
How to Use glob() in Python | note.nkmk.me
July 28, 2023 - Get the filename, directory, extension from a path string in Python · print([os.path.basename(p) for p in glob.glob('temp/**', recursive=True) if os.path.isfile(p)]) # ['[x].txt', '12.jpg', 'aaa.jpg', '987.jpg', 'ccc.jpg', '98.txt', 'bbb.txt', 'ddd.jpg', '1.txt', '123.txt'] ... If you want to retain information about the intermediate directory, specify the root_dir argument. As mentioned above, when root_dir is set, the result is a relative path from root_dir, so pass it to os.path.isfile() after concatenating with root_dir.
🌐
CodeFatherTech
codefather.tech › home › blog › filename pattern matching with the python glob module
Filename Pattern Matching with the Python glob Module
December 8, 2024 - The glob() function of the Python glob module returns results in arbitrary order. The path we provide to the glob() function can be absolute or relative.
Find elsewhere
🌐
Python Packaging
packaging.python.org › en › latest › specifications › glob-patterns
glob patterns - Python Packaging User Guide
Special glob characters: *, ?, ** and character ranges: [] containing only the verbatim matched characters MUST be supported. Within [...], the hyphen indicates a locale-agnostic range (e.g. a-z, order based on Unicode code points). Hyphens at the start or end are matched literally. Path delimiters MUST be the forward slash character (/). Patterns always refer to relative paths, e.g., when used in pyproject.toml, patterns should always be relative to the directory containing that file.
🌐
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. If pathname is relative, the result will contain paths relative to root_dir.
🌐
Python Module of the Week
pymotw.com › 2 › glob
glob – Filename pattern matching - Python Module of the Week
The patterns rules are applied to segments of the filename (stopping at the path separator, /). Paths in the pattern can be relative or absolute. Shell variable names and tilde (~) are not expanded. The examples below assume the following test files are present in the current working directory: $ python glob_maketestdata.py dir dir/file.txt dir/file1.txt dir/file2.txt dir/filea.txt dir/fileb.txt dir/subdir dir/subdir/subfile.txt
🌐
Michael Currin
michaelcurrin.github.io › dev-cheatsheets › cheatsheets › python › files-and-paths › glob.html
Glob | Dev Cheatsheets
glob.glob(pathname, *, recursive=False) Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname · can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools//.gif), and can contain shell-style wildcards.
🌐
GitHub
github.com › python › cpython › blob › main › Lib › glob.py
cpython/Lib/glob.py at main · python/cpython · GitHub
# This helper function recursively yields relative pathnames inside a literal · # directory. · def _glob2(dirname, pattern, dir_fd, dironly, include_hidden=False): assert _isrecursive(pattern) if not dirname or _isdir(dirname, dir_fd): yield pattern[:0] yield from _rlistdir(dirname, dir_fd, dironly, include_hidden=include_hidden) ·
🌐
Python
docs.python.org › 3 › library › pathlib.html
pathlib — Object-oriented filesystem paths — Python 3.15.2 documentation
Match this path against the provided non-recursive glob-style pattern. Return True if matching is successful, False otherwise. This method is similar to full_match(), but empty patterns aren’t allowed (ValueError is raised), the recursive wildcard “**” isn’t supported (it acts like non-recursive “*”), and if a relative pattern is provided, then matching is done from the right:
🌐
Astrofrog
astrofrog.github.io › py4sci › _static › 12. Files and paths.html
12. Files and paths
The built-in glob module allows you to do something similar from Python. The only important function here in the glob module is also called glob. This function can be given a pattern (such as *.py) and will return a list of filenames that match: ... ['10. Introduction to Numpy.ipynb', 'Practice Problem - Monte-Carlo Error Propagation - Sample Solution.ipynb', 'Problem Set 2.ipynb', '11. Introduction to Matplotlib.ipynb', 'Wednesday Exercise Solutions.ipynb', '13. String Formatting.ipynb', '12. Files and paths.ipynb', 'Practice Problem - Monte-Carlo Error Propagation.ipynb']
🌐
Python
docs.python.org › 3.9 › library › glob.html
glob — Unix style pathname pattern expansion — Python 3.9.25 documentation
July 8, 2025 - glob.glob(pathname, *, recursive=False)¶ · Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards.