Python Academy · Lesson

Globbing and Iterating

Find files with glob patterns.

Lesson 3 of 413 steps

Globbing and Iterating is a free Python Academy lesson on CoddyKit. This is lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, and your progress syncs across the web and the CoddyKit app. The Python Academy course includes 4 lessons in total.

Finding Files

pathlib makes it easy to list directory contents and search for files matching a pattern. The key methods are iterdir, glob, and rglob.

Setting Up a Sample Tree

To explore these methods we first build a small directory of files. This setup uses only the standard library.

from pathlib import Path

root = Path('sample')
root.mkdir(exist_ok=True)
(root / 'a.txt').write_text('1')
(root / 'b.txt').write_text('2')
(root / 'c.log').write_text('3')
print('created files')

iterdir Lists Contents

iterdir() yields each entry directly inside a directory, one Path per item.

from pathlib import Path

root = Path('sample')
for entry in sorted(root.iterdir()):
    print(entry.name)

glob with a Pattern

glob() finds entries matching a shell-style pattern. The * wildcard matches any run of characters.

from pathlib import Path

root = Path('sample')
for txt in sorted(root.glob('*.txt')):
    print(txt.name)

Single-Character Wildcard

The ? wildcard matches exactly one character, useful for fixed-width names.

from pathlib import Path

root = Path('sample')
for m in sorted(root.glob('?.txt')):
    print(m.name)

Character Ranges

Square brackets match any one character from a set or range, just like in shell globbing.

from pathlib import Path

root = Path('sample')
for m in sorted(root.glob('[ab].txt')):
    print(m.name)

Recursive glob with rglob

rglob() searches a directory and all of its subdirectories. It is equivalent to glob('**/pattern').

from pathlib import Path

root = Path('sample')
(root / 'nested').mkdir(exist_ok=True)
(root / 'nested' / 'deep.txt').write_text('x')
for m in sorted(root.rglob('*.txt')):
    print(m)

Counting Matches

Glob results are iterators. Wrap one in list() to count or reuse the matches.

from pathlib import Path

root = Path('sample')
txts = list(root.rglob('*.txt'))
print('found', len(txts), 'text files')

Filtering While Iterating

Combine globbing with the is_file or is_dir checks to filter results precisely.

from pathlib import Path

root = Path('sample')
files = [p for p in root.iterdir() if p.is_file()]
for f in sorted(files):
    print(f.name)

Processing Found Files

Once you have the matches, you can read each file. Here we sum the contents of every text file in the tree.

from pathlib import Path

root = Path('sample')
total = 0
for p in root.rglob('*.txt'):
    text = p.read_text().strip()
    if text.isdigit():
        total += int(text)
print('total:', total)

Sorting Glob Results

Glob does not guarantee any particular order. Wrap the results in sorted() when you need deterministic output, for example when building a report.

from pathlib import Path

root = Path('sample')
for p in sorted(root.glob('*'), key=lambda x: x.name):
    print(p.name)

Quick Check

What is the difference between glob and rglob?

Recap

You learned to find files with glob patterns.

  • iterdir lists direct contents.
  • glob matches a pattern (*, ?, [...]).
  • rglob searches recursively.
  • Combine globbing with is_file/is_dir filters and read the matches.
Free to start

Learn Python with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
76
Lessons
320

Frequently Asked Questions

Is the “Globbing and Iterating” lesson free?

Yes — the full text of “Globbing and Iterating” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO. The Python Academy course includes 4 lessons in total.

What will I learn in “Globbing and Iterating”?

Find files with glob patterns. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Globbing and Iterating” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Path Object
  2. Reading and Writing Files
  3. Globbing and Iterating
  4. Path Manipulation
← Back to Python Academy