CodeBlanks Logo Icon CodeBlanks

glob and rglob

Learn pattern search with glob and rglob.

Finding files with glob

To search files in a folder by pattern you use p.glob("*.txt"). The return is a generator; to get a list write list(p.glob("*.txt")). The pattern matches anything with * and a single character with ?.

The rglob method also descends into subfolders; it searches recursively. For instance p.rglob("*.py") searches for .py files in p and all its subfolders. It's a useful tool in big projects.

Practice Find files with glob

Start with from pathlib import Path. Create a path with d = Path("test_dir") and make the folder with d.mkdir(). Create three files: (d / "a.txt").write_text("x", encoding="utf-8"), (d / "b.txt").write_text("y", encoding="utf-8") and (d / "c.md").write_text("z", encoding="utf-8"). Then find txt files with results = list(d.glob("*.txt")) and print the count with print(len(results)).

Starter code

main.py
# Import the Path class
# Create the d folder
# Write three files (two txt, one md)
# Find txt files with glob, print the count

Sample solution

main.py
# Import the Path class
from pathlib import Path
# Create the d folder
d = Path("test_dir")
d.mkdir()
# Write three files (two txt, one md)
(d / "a.txt").write_text("x", encoding="utf-8")
(d / "b.txt").write_text("y", encoding="utf-8")
(d / "c.md").write_text("z", encoding="utf-8")
# Find txt files with glob, print the count
results = list(d.glob("*.txt"))
print(len(results))

Expected output

2

Pattern syntax

glob patterns have simple syntax. * matches zero or more characters, ? matches exactly one. [abc] matches one of the listed characters, [0-9] matches a digit. For example the pattern "file?.txt" matches file1.txt but not file12.txt.

For more complex patterns you'd use the re module; glob patterns are not regex. This restriction is intentional; it keeps patterns simple and predictable.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What's the difference between glob and rglob?

  • glob searches one folder, rglob also walks subfolders Correct answer
  • glob finds files, rglob finds folders only
  • glob returns strings, rglob returns lists
  • They are exactly the same

Explanation: Glob searches one folder, rglob also walks subfolders.

2 Complete the rglob call

Question
for py_file in p.____("*.py"):
    print(py_file.name)
Answer
for py_file in p.rglob("*.py"):
    print(py_file.name)

Explanation: rglob also walks subfolders.

3 Match the pattern symbols

Term Meaning
* Zero or more characters
? Single character
[abc] One character from a list
rglob Recursive search

All lessons in Intermediate