Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 10 · Production idioms (modern Python)pathlib.Path — the modern alternative to os.path string-pushingpredict142 / 161
+150 XP
Task
📝 **Task:** Predict the 8-line output. A temp directory is created; a file is written + read; the path is decomposed by .name / .stem / .suffix; .with_suffix produces a derived name; .glob finds two .py files; .exists distinguishes a real file from a non-existent one. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

from pathlib import Path
import tempfile


with tempfile.TemporaryDirectory() as tmpdir:
    base = Path(tmpdir)

    f = base / "data.txt"
    f.write_text("hello\nworld\n")

    # 1. round-trip read
    print(f.read_text().strip())

    # 2. path decomposition
    print(f.name)
    print(f.stem)
    print(f.suffix)

    # 3. derived path via .with_suffix
    new = f.with_suffix(".bak")
    print(new.name)

    # 4. glob
    (base / "a.py").write_text("")
    (base / "b.py").write_text("")
    print(sorted(p.name for p in base.glob("*.py")))

    # 5. exists predicate
    print(f.exists(), (base / "ghost.txt").exists())

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…