Python Central HubSign in

Automation and Scripting / Phase 1: OS & File System Automation

Pattern Matching with glob

Find files using wildcard patterns like *.txt and **/*.py.

diagram the three things glob quietly does not do mermaid
A pattern that looks like it should match everything usually does not. Two stars only recurse if you ask for recursion, a leading dot has to be matched explicitly, and case sensitivity depends on the filesystem rather than on your pattern. All three were measured on the same small tree.

What glob does

glob finds files using wildcard patterns:

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

Using glob module

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

Recursive glob

Python
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

exerciseYour turn

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

exerciseYour turn

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

exerciseYour turn

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.

Was this page helpful?

Let us know how we did