smartyfy.mrindigi.com

Python Master Course V2 — 074. Pathlib and Directory Traversal

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 07 · LESSON 074 OF 200

Pathlib and Directory Traversal

Study time: 75–100 minutes · Prerequisites: functions, exceptions, pathlib and Lesson 73.

Course hub

Video lesson

Video not yet available. Reserved for a verified lesson video URL/player.

Learning outcomes

Enumerate files and reason about path boundaries. You will also identify failure cases, predict outputs, apply the concept in a small application, and test the result.

Understand Pathlib and Directory Traversal

Traversal is more than constructing a path

Directory traversal visits the entries below a chosen root. A shallow inventory examines immediate children; a recursive inventory also descends into subdirectories. The report should use paths relative to the selected root so it is portable and does not expose unrelated machine-specific locations. Constructing a path with pathlib does not traverse anything; iterdir or another enumeration operation must actually read the directory.

This teaching scanner is read-only after fixture creation. Its policy is to inspect regular files, descend into regular directories, skip symbolic links, avoid revisiting resolved directories and report inspection errors. It is intended for a trusted, non-changing practice tree. The explicit stack stores pending directories, avoiding dependence on Python’s recursive call-depth limit. A sorted final report gives deterministic display even though filesystem enumeration order is not guaranteed.

Python — Complete traversal with disposable fixture
from pathlib import Path
import stat

def inventory_tree(folder):
    initial = Path(folder)
    if not stat.S_ISDIR(initial.lstat().st_mode):
        raise ValueError("root must be a real directory, not a symlink")
    root = initial.resolve(strict=True)
    pending = [root]
    visited = {root}
    rows, errors = [], []
    inspected = 0
    while pending:
        directory = pending.pop()
        try:
            entries = list(directory.iterdir())
        except OSError as error:
            errors.append((directory.relative_to(root).as_posix(), type(error).__name__))
            continue
        for entry in entries:
            inspected += 1
            if inspected > 10000:
                raise ValueError("practice inventory entry limit exceeded")
            label = entry.relative_to(root).as_posix()
            try:
                info = entry.lstat()
                if stat.S_ISLNK(info.st_mode):
                    errors.append((label, "symlink skipped"))
                    continue
                resolved = entry.resolve(strict=True)
                if not resolved.is_relative_to(root):
                    errors.append((label, "outside root skipped"))
                elif stat.S_ISDIR(info.st_mode):
                    if resolved in visited:
                        errors.append((label, "already visited"))
                    else:
                        visited.add(resolved)
                        pending.append(entry)
                elif stat.S_ISREG(info.st_mode):
                    rows.append((label, info.st_size))
            except (OSError, RuntimeError) as error:
                errors.append((label, type(error).__name__))
    return sorted(rows), sorted(errors)

from tempfile import TemporaryDirectory

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    (root / "nested").mkdir()
    (root / "a.txt").write_bytes(b"Hi")
    (root / "nested" / "b.txt").write_bytes(b"ABC")
    rows, errors = inventory_tree(root)
    print(rows)
    print(errors)
Expected output
[('a.txt', 2), ('nested/b.txt', 3)]
[]

Follow the scan in stages

The root is checked before it is resolved so a direct symbolic-link root is rejected. Each directory is enumerated inside a try block, covering failures that happen before any child is processed. lstat inspects the entry itself rather than following a symbolic link for metadata. Resolved paths are checked against the chosen root, and the visited set avoids returning to a directory already scheduled. File rows retain the relative display path and byte size.

The errors list distinguishes skipped links from operational failures such as PermissionError. A caller can display partial results with warnings or decide any error makes the inventory incomplete. The entry budget stops a practice scan from continuing indefinitely through an unexpectedly large tree. It is a teaching limit, not a sophisticated resource quota: listing one very large directory can still allocate a large list before that count is checked.

Understand what the checks cannot guarantee

A path may change between lstat, resolve and later enumeration. Therefore these checks do not make the scanner safe against a hostile process changing the tree concurrently. Symlinks, platform-specific junctions, mounts and permissions have filesystem-specific behavior. The resolved-root and visited checks improve predictable traversal in the stated practice setting; they are not substitutes for operating-system isolation or race-resistant file-descriptor APIs in security-sensitive software.

Do not implement containment by string prefix: a directory named reports-backup can share the text prefix reports without being its child. Path-aware relative checks compare components. Also avoid accepting an arbitrary absolute child path and assuming that joining it to the root keeps it inside; an absolute component can replace the earlier base. Test an empty tree, a nested file, a missing root and, where the platform permits, a skipped link. The pathlib reference documents resolution and relative-path behavior.

Path-component warmup

This original sample describes a path without reading a directory; the traversal example above performs the scan.

Requires Python 3.10+. Run in a disposable practice folder. Save as lesson74.py and execute with python lesson74.py or python3.

from pathlib import Path
p=Path('reports')/'2026'/'summary.csv'
print(p.name)
print(p.parent.name)
print(p.suffix)

Expected output:

summary.csv
2026
.csv

How to reason through the example

Identify which operation opens, parses, writes or transforms data. Trace each value from source to output. Note whether any file is created and whether repeated execution changes the result. Next, alter one value, predict the result, run the example and compare your prediction.

Additional code exercise — Empty and missing roots

Run after defining inventory_tree above in the same script. Compare a successfully scanned empty tree with a missing root.

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    assert inventory_tree(root) == ([], [])
    try:
        inventory_tree(root / "missing")
    except FileNotFoundError:
        print("missing root reported")
    else:
        raise AssertionError("missing root was accepted")

Expected: missing root reported. An inaccessible or missing root must not be reported as a successfully scanned empty tree.

Guided practical project

Project brief: Build a read-only recursive inventory for a trusted practice tree, with skipped symlinks and an error report.

  1. Specify input format, accepted fields and error policy.
  2. Create a small sample dataset with three valid and two invalid records.
  3. Write a parser and validator that report errors with record numbers.
  4. Implement the transformation as a separate testable function.
  5. Write results to a different destination rather than overwriting source files.
  6. Test empty, malformed, boundary and ordinary cases.
  7. Document setup, expected output and recovery procedure.

Mastery requirements: at least three automated tests, explicit error handling and a reproducible example. This is an assignment, not a claim that the complete project has been executed on the website.

Common mistakes and debugging

  • Assuming the process working directory is the same as the script directory.
  • Relying on platform-dependent encodings.
  • Trusting records without checking required fields or types.
  • Overwriting input files before verifying transformed output.
  • Catching every exception and hiding the underlying failure.

Debug systematically: reproduce a failure with the smallest record, inspect the exception and offending input, correct the cause, and add a regression test.

Practice and explained answers

Try each question before opening its answer. Predict code results on paper, then compare them with the explanation.

Optional hint for question 1

Ask whether an enumeration error can happen before any child reaches the loop body.

1. Why is iterdir wrapped in a try block outside the entry loop?

Answer and reasoning:

Opening or consuming the directory iterator can fail before a child is yielded. A try only inside the loop body would not handle an enumeration-level PermissionError or disappearance.

2. What is the difference between stat and lstat for a symbolic link?

Answer and reasoning:

stat normally follows the link to inspect its target. lstat inspects the link entry itself. The latter allows the scanner to classify and skip direct symbolic links before following their targets.

3. Why is a string-prefix check not a containment test?

Answer and reasoning:

The text /data/reports-old starts with /data/reports but is not inside that directory. Path component checks such as is_relative_to on deliberately resolved paths reflect hierarchy more accurately. They still do not remove race conditions.

4. Why return errors instead of silently skipping failures?

Answer and reasoning:

A report with missing files may otherwise look complete. Returning the affected relative path and error class lets the caller make an explicit decision about partial results and preserves useful troubleshooting information.

5. Does the skipped-symlink policy guarantee hostile-tree safety?

Answer and reasoning:

No. The filesystem can change between inspection and use, and platform-specific link-like structures require careful handling. Use this example on trusted practice trees; stronger isolation and race-resistant APIs are needed for adversarial inputs.

Knowledge check

Use the topic-specific practice questions above to check your understanding. Attempt each answer before opening its explanation.

Return to the practice questions ↑

Mastery checkpoint

Demonstrate the sample, explain its output, implement the project, test three edge cases, and describe your error-handling policy. The video remains unavailable and learner completion is not account-synchronized.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.