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
glob finds files using wildcard patterns:
*.txtdata_??.csv- recursive patterns with
**
Using glob module
from glob import glob
for path in glob("*.py"):
print(path)Recursive glob
from glob import glob
for path in glob("**/*.md", recursive=True):
print(path)Prefer pathlib
pathlib.Path.rglob is often cleaner.
๐งช Try It Yourself
Exercise 1 โ List Files with os.listdir
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.Exercise 2 โ Join Paths with os.path.join
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.Exercise 3 โ Write and Read a File
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.