Sub topic 10
Finding files with glob and rglob
This chapter covers Path.glob() and Path.rglob(), the pathlib methods that search a directory for names matching a pattern. It assumes you can already build Path objects, use exists(), is_file() and is_dir(), and create directories with mkdir(). It also assumes you know what a generator is and how to loop over one.
What glob does
glob is a method on a directory path. It takes a pattern and yields every entry below that directory whose path matches the pattern. Each result is a Path object. It is built from the directory you called it on, so the results can be joined, split, and passed to read_text() like any other path.
from pathlib import Path
import tempfile
def make_tree(root):
for rel in ["a.py", "b.txt", ".hidden.py",
"pkg/c.py", "pkg/sub/d.py", "pkg/sub/e.md"]:
f = root / rel
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text("x\n", encoding="utf-8")
def show(paths, root):
print(sorted(p.relative_to(root).as_posix() for p in paths))
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
make_tree(root)
show(root.glob("*.py"), root) # ['.hidden.py', 'a.py']
show(root.glob("*/*.py"), root) # ['pkg/c.py']
show(root.glob("*"), root) # ['.hidden.py', 'a.py', 'b.txt', 'pkg']The code uses a temporary directory so you can run it anywhere and nothing is left behind. Three details matter here:
root.glob("*")returns files and directories. The pattern only looks at names.- The pattern
*.pymatches only the top level. It does not descend intopkg. .hidden.pyis matched. Unlike shell globbing, pathlib does not treat a leading dot specially.
Pattern syntax
Patterns follow the rules of the fnmatch module, with one addition for recursion.
| Pattern | Matches | Example |
|---|---|---|
| `*` | Zero or more characters within one name | `*.txt` |
| `?` | Exactly one character | `log?.txt` matches `log1.txt` |
| `[abc]` | One character from the set | `data[0-9].csv` |
| `[!abc]` | One character not in the set | `[!_]*.py` |
| `**` | Zero or more directory levels | `**/*.py` |
* and ? never match the path separator. A pattern like */*.py is therefore split into components, and each component is matched against one directory level.
Braces such as *.{py,md} are not supported. Pathlib treats the braces as literal characters, so the pattern finds nothing. To match several extensions, filter by suffix as shown later.
Recursive search with `**` and `rglob`
rglob(pattern) is the same as glob("**/" + pattern). It searches the directory and every subdirectory beneath it.
from pathlib import Path
import tempfile
def make_tree(root):
for rel in ["a.py", "b.txt", ".hidden.py",
"pkg/c.py", "pkg/sub/d.py", "pkg/sub/e.md"]:
f = root / rel
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text("x\n", encoding="utf-8")
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
make_tree(root)
for pattern in ["**/*.py", "pkg/**/*.py"]:
names = sorted(p.relative_to(root).as_posix() for p in root.glob(pattern))
print(pattern, names)
names = sorted(p.relative_to(root).as_posix() for p in root.rglob("*.py"))
print("rglob", names)The first line lists every .py file in the whole tree. That includes a.py at the top, because ** can match zero directories. The second line lists only pkg/c.py and pkg/sub/d.py, because the pattern starts inside pkg. The rglob line gives the same result as the first.
Version differences
Behavior changed across Python releases, so check your version before relying on edge cases:
- A pattern that ends in
**(for exampleroot.glob("**")) returned only directories before Python 3.13. From 3.13 it returns files and directories. - A pattern such as
**.pyraisesValueError, because**must be a whole path component. Write**/*.pyinstead. - Python 3.12 added the
case_sensitiveargument. Python 3.13 addedrecurse_symlinks, which controls whether**follows symbolic links to directories.
Results are lazy and unordered
glob and rglob return a generator. The file system is read as you loop, not when you call the method. This has three consequences:
- You can stop early with
breakornext(), and the rest of the tree is never scanned. - You can loop over the result only once. To reuse it, wrap it in
list(). - The order is whatever the operating system returns. It can differ between machines and runs.
Use sorted() whenever the output is shown to people, written to a file, or compared in a test.
Also collect the results into a list before you rename or delete what you found. Changing a directory while a generator is walking it can skip entries or raise errors.
Filtering results
A pattern only inspects names. Everything else needs a Python condition.
- Files only. Directories can match too, for example a folder named
data.py. Addp.is_file(). - Several extensions. Test
p.suffix.lower() in {".jpg", ".jpeg", ".png"}. Lowercasing also handles files namedPHOTO.JPG. - Skipping directories.
rglobhas no way to exclude a directory such as.gitornode_modules. It still walks them, and you filter afterwards.
This function combines all three:
from pathlib import Path
import tempfile
def find_files(root, suffixes, skip_dirs=()):
root = Path(root)
wanted = {s.lower() for s in suffixes}
skip = set(skip_dirs)
found = []
for p in root.rglob("*"):
parent_dirs = p.relative_to(root).parts[:-1]
if skip.intersection(parent_dirs):
continue
if p.is_file() and p.suffix.lower() in wanted:
found.append(p)
return sorted(found)
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
for rel in ["app/main.py", "app/UTIL.PY", "app/notes.md",
".git/hooks/x.py", "node_modules/lib/y.py"]:
f = root / rel
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text("x\n", encoding="utf-8")
for p in find_files(root, [".py"], skip_dirs=[".git", "node_modules"]):
print(p.relative_to(root).as_posix())The function prints app/main.py and app/UTIL.PY. The order depends on how your platform compares names. The .git and node_modules files are skipped because their directory names appear in the parent parts. The test uses relative_to(root) so that a directory named .git above the search root does not exclude everything.
Case sensitivity
Matching follows the platform by default. On Linux, *.JPG does not match photo.jpg. On Windows it does. Code that depends on this will behave differently across systems. Two portable options are:
- Search broadly and filter with
suffix.lower(), as above. - On Python 3.12 or later, pass
case_sensitive=Falseorcase_sensitive=Truetogloborrglobto force one behavior.
Large trees and pruning
rglob("*") visits every entry, including ones you plan to discard. For a project with a big dependency folder, that can take seconds. If you need to prune whole branches, Python 3.12 added Path.walk(). It works like os.walk(), and you can remove names from its directory list so they are never entered. For typical project-sized searches, rglob with a filter is simpler and fast enough.
Common mistakes
- Expecting an error when nothing matches. An empty result is normal. A typo in the pattern and a missing directory both produce an empty iterator. Check
root.is_dir()first if that distinction matters. - Calling glob on a file. It yields nothing. The path must be a directory.
- Absolute or empty patterns.
root.glob("/etc/*")raisesNotImplementedError, androot.glob("")raisesValueError. Build the base directory as aPathand keep the pattern relative to it. - Special characters in directory names. A directory called
data[2026]would be read as a character set if it were inside the pattern. Put it in thePathinstead:Path("data[2026]").glob("*.csv"). - Assuming dotfiles are skipped. Pathlib returns them. Filter on
p.name.startswith(".")if you want to drop them.
Exercise
You run list(Path("logs").rglob("*.log")) and get results that include a directory named old.log. How do you keep only real files, and how do you make the result match *.LOG files as well on any operating system?
Show answer
Filter with is_file() and compare the lowercased suffix: [p for p in Path("logs").rglob("*") if p.is_file() and p.suffix.lower() == ".log"]. The pattern * matches every name, so the case comparison is done in Python and behaves the same on all platforms. On Python 3.12 or later, rglob("*.log", case_sensitive=False) also works, but it still needs an is_file() check.
Exercise
What does bool(Path("reports").glob("*.csv")) return when the folder contains no CSV files, and what should you write instead to test for at least one match?
Show answer
It returns True, because a generator object is always truthy. Use any(Path("reports").glob("*.csv")) or next(Path("reports").glob("*.csv"), None) is not None. Both stop after the first match.