Skip to content

Pattern Matching with glob

What glob does

globglob finds files using wildcard patterns:

  • *.txt*.txt
  • data_??.csvdata_??.csv
  • recursive patterns with ****

Using globglob module

glob_basic.py
from glob import glob
 
for path in glob("*.py"):
    print(path)
glob_basic.py
from glob import glob
 
for path in glob("*.py"):
    print(path)

Recursive glob

glob_recursive.py
from glob import glob
 
for path in glob("**/*.md", recursive=True):
    print(path)
glob_recursive.py
from glob import glob
 
for path in glob("**/*.md", recursive=True):
    print(path)

Prefer pathlib

pathlib.Path.rglobpathlib.Path.rglob is often cleaner.

๐Ÿงช Try It Yourself

Exercise 1 โ€“ List Files with os.listdir

Exercise 2 โ€“ Join Paths with os.path.join

Exercise 3 โ€“ Write and Read a File

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did