This guide explains pathlib.path.glob() method: usage and examples through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
Path.glob(pattern) yields paths matching a pattern relative to a directory. Patterns such as *.txt match immediate text files; **/*.txt searches through nested folders.
When and Why to Use It
The following example focuses on a practical use of pathlib.Path.glob() Method: Usage and Examples.
Step-by-Step Example
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
root_directory = Path(directory)
(root_directory / "notes.txt").write_text("a", encoding="utf-8")
nested_directory = root_directory / "archive"
nested_directory.mkdir()
(nested_directory / "old.txt").write_text("b", encoding="utf-8")
print(sorted(path.name for path in root_directory.glob("*.txt")))
print(sorted(path.relative_to(root_directory).as_posix() for path in root_directory.glob("**/*.txt")))
Understanding the Example
The first pattern finds only notes.txt at the root. The recursive pattern also finds archive/old.txt, which is displayed using a path relative to the root.
Expected Output
['notes.txt']
['archive/old.txt', 'notes.txt']
Important Behavior and Edge Cases
glob results are not promised in a particular order, and wildcard matches may include directories for some patterns. Filter with is_file if needed.
Try It Yourself
Find every .csv file in a test directory using a recursive pattern, sorting results for display.
For file examples, use a dedicated practice directory or a temporary directory. Make sure you understand whether a call reads, creates, overwrites or appends before using it on important files.
Common Beginner Mistakes
- glob results are not promised in a particular order, and wildcard matches may include directories for some patterns. Filter with is_file if needed.
- Assuming the current working directory, encoding, filesystem contents or file permissions will be identical on every computer.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- Path.glob(pattern) yields paths matching a pattern relative to a directory.
- The first pattern finds only notes.txt at the root.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.