Python
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.
Exercise 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)).
Show example solution
# 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))
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.
Test yourself
-
What's the difference between glob and rglob?
- glob searches one folder, rglob also walks subfolders
- glob finds files, rglob finds folders only
- glob returns strings, rglob returns lists
- They are exactly the same
Show answer
glob searches one folder, rglob also walks subfolders — Glob searches one folder, rglob also walks subfolders.
-
Complete the rglob call
for py_file in p.____("*.py"):
print(py_file.name)
Show answer
for py_file in p.rglob("*.py"):
print(py_file.name)
-
Match the pattern symbols
- *
- Zero or more characters
- ?
- Single character
- [abc]
- One character from a list
- rglob
- Recursive search
Next lesson: Summary - Pathlib