Skip to content
Foxipa
Code Completion 4 Challenges

Complete the glob and fnmatch code

Practise rooted pathname matching, lazy recursive search, explicit case-sensitive matching, and literal pattern escaping.

Intermediate ~12 min read

Challenge 1

List the CSV pathnames directly under the chosen root, sorted by name.

python Your answer
import glob
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    (root / "one.csv").touch()
    (root / "two.txt").touch()
    matches = sorted(glob.glob()
    assert matches == ["one.csv"]
    print(matches)

Press Ctrl⌘Enter to check your answer

Challenge 2

Count log files recursively without collecting all matched names into a list.

python Your answer
import glob
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    (root / "deep").mkdir()
    (root / "one.log").touch()
    (root / "deep" / "two.log").touch()
    count = sum(1 for _ in glob.iglob(")
    assert count == 2
    print(count)

Press Ctrl⌘Enter to check your answer

Challenge 3

Keep only names whose lowercase .csv suffix matches exactly, regardless of operating-system case rules.

python Your answer
import fnmatch

names = ["report.csv", "REPORT.CSV", "summary.txt"]
matched = [name for name in names if ]
assert matched == ["report.csv"]
print(matched)

Press Ctrl⌘Enter to check your answer

Challenge 4

Turn the literal name into a glob pattern that matches its brackets as filename characters.

python Your answer
import glob

name = "release[final].csv"
pattern = 
assert pattern == glob.escape(name)
print(pattern)

Press Ctrl⌘Enter to check your answer