Skip to content
Foxipa
Code Completion 5 Challenges

Complete the os.scandir() code

Practise scanning directories, filtering DirEntry objects, handling cached status data, and closing iterators safely.

Intermediate ~12 min read

Challenge 1

Complete the context-manager alias for the directory iterator.

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

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    (root / "item.txt").touch()
    with os.scandir(root) as :
        names = sorted(entry.name for entry in entries)
    print(names)

Press Ctrl⌘Enter to check your answer

Challenge 2

Use DirEntry to select regular files without following symbolic links.

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

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    (root / "data.txt").touch()
    with os.scandir(root) as entries:
        files = sorted(entry.name for entry in entries if entry.)
    print(files)

Press Ctrl⌘Enter to check your answer

Challenge 3

Make directory-scan results deterministic by completing the built-in function.

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

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    (root / "z.txt").touch()
    (root / "a.txt").touch()
    with os.scandir(root) as entries:
        names = (entry.name for entry in entries)
    print(names)

Press Ctrl⌘Enter to check your answer

Challenge 4

Fetch fresh status data after the scanned file has changed.

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

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    path = root / "data.txt"
    path.write_bytes(b"old")
    with os.scandir(root) as entries:
        entry = next(entries)
        cached_size = entry.stat().st_size
        path.write_bytes(b"new content")
        current_size = os.(entry.path).st_size
        assert cached_size == 3 and current_size == 11
        print(cached_size, current_size)

Press Ctrl⌘Enter to check your answer

Challenge 5

Catch the standard exception for a directory that does not exist.

python Your answer
import os

try:
    with os.scandir("missing-directory") as entries:
        list(entries)
except :
    print("directory is missing")

Press Ctrl⌘Enter to check your answer