Pattern Matching with glob
flowchart TD
A["glob('*.txt')"] --> B["the current directory only"]
C["glob('**/*.txt')"] --> D["still one level -- ** acts like * without recursive=True"]
E["glob('**/*.txt', recursive=True)"] --> F["every depth, including the top"]
G["a dotfile like .hidden.txt"] --> H["never matched by * -- needs '.*' explicitly"]
I["b.TXT vs pattern *.txt"] --> J["matched here on Windows; would NOT on Linux"]
F --> K["for recursion, Path('.').rglob('*.txt') is clearer"]
H --> L["and rglob DOES return dotfiles -- the two differ"]
What glob does
Section titled “What glob does”glob finds files using wildcard patterns:
*.txtdata_??.csv- recursive patterns with
**
Using glob module
Section titled “Using glob module”from glob import glob
for path in glob("*.py"):
print(path)Recursive glob
Section titled “Recursive glob”from glob import glob
for path in glob("**/*.md", recursive=True):
print(path)Prefer pathlib
Section titled “Prefer pathlib”pathlib.Path.rglob is often cleaner.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading