Sub topic 10
Finding files with glob and rglob
This chapter assumes you can build Path objects, use / to join them, and check is_file() and is_dir(). It also assumes you can write a basic for loop. Here you will search a directory for files whose names match a pattern.
What glob does
Path.glob(pattern) looks inside a directory and yields every path whose name matches a wildcard pattern. Path.rglob(pattern) does the same search through the directory and all its subdirectories. Both return a generator of Path objects, so you can loop over the results without building a list first.
| Pattern part | Matches |
|---|---|
| `*` | Any run of characters within one name, including none |
| `?` | Exactly one character |
| `[0-9]` | One character from the set or range |
| `**` | The directory itself and every directory below it |
A runnable example
The script below builds a small tree in a temporary directory, so you can run it as shown.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "pkg" / "sub").mkdir(parents=True)
names = [
"main.py", "notes.txt", "pkg/util.py",
"pkg/sub/deep.py", "pkg/data1.csv", "pkg/data22.csv",
]
for name in names:
(root / name).write_text("x\n", encoding="utf-8")
def show(paths):
print(sorted(p.relative_to(root).as_posix() for p in paths))
show(root.glob("*.py")) # ['main.py']
show(root.rglob("*.py")) # ['main.py', 'pkg/sub/deep.py', 'pkg/util.py']
show(root.glob("**/*.py")) # same as the rglob line above
show(root.glob("pkg/data?.csv")) # ['pkg/data1.csv']
show(root.glob("pkg/data[0-9]*.csv")) # ['pkg/data1.csv', 'pkg/data22.csv']glob("*.py") looks only at the top level, so it misses pkg/util.py. rglob("*.py") is shorthand for glob("**/*.py").
Filtering and ordering results
A pattern matches both files and directories. A directory named backup.py would match *.py. Filter the results when the type matters:
from pathlib import Path
py_files = sorted(p for p in Path("src").rglob("*.py") if p.is_file())
subdirs = [p for p in Path("src").glob("*") if p.is_dir()]The order of results depends on the file system, so wrap the call in sorted() whenever you print results or compare them in tests. A generator is also used up after one pass. Call list() on it if you need to loop twice.
Behavior that differs from the shell
- Hidden files match. In a shell,
*skips names starting with a dot. Inpathlib,*matches.envand.git, andrglob("*")walks into hidden directories. - Case sensitivity follows the operating system. Patterns are case-insensitive on Windows and usually case-sensitive on Linux. Python 3.12 adds a
case_sensitiveargument to make this explicit. - Patterns must be relative.
Path("src").glob("/etc/*")raisesNotImplementedError. Create thePathfor the starting directory, then givegloba relative pattern. - A missing starting directory is not an error. Searching
Path("nope").glob("*")yields nothing, so a typo in a directory name looks like "no files found". Checkis_dir()first if that matters.
Matching several extensions
A pattern has no "or" syntax such as *.{jpg,png}. Use a loop or a filter on suffix:
from pathlib import Path
images = sorted(
p for p in Path("photos").rglob("*")
if p.is_file() and p.suffix.lower() in {".jpg", ".jpeg", ".png"}
)This also fixes case differences, because suffix.lower() treats .JPG and .jpg the same.
Exercise
You run list(Path("project").glob("*.txt")) and expect to find project/docs/readme.txt, but the list is empty. Which change fixes this, and what should you add if some matches might be directories?
Show answer
glob("*.txt") searches only the top level of project. Use rglob("*.txt") or glob("**/*.txt") to search subdirectories. If directories could match, add a filter such as if p.is_file().