Ch. 9 · Python

Python Pathlib and Safe File Selection

Python Pathlib and Safe File Selection. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readadvancedupdated Oct 3, 2026

Pathlib models path operations clearly but does not authorize access. External filenames need containment and ownership checks.

Before you start

You should know Python functions, collections and exceptions. Use a small isolated script or interactive session to trace the example. Pay attention to when objects are created and when work executes; iteration, binding and mutation can happen at different points in a program.

The practical goal is to reason through this situation: Resolve a requested path relative to an allowed root before deciding whether to read it. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Resolve authorized selection

Map a validated file ID to an allowed server-controlled path where possible.

Step 2: Check containment

Path operations simplify reasoning but do not establish access permission.

The filesystem may resolve differently from a prior lexical check.

Worked scenario

Resolve a requested path relative to an allowed root before deciding whether to read it.

A user requests report 42, and the application checks ownership before mapping it to a path. Accepting an arbitrary filename and calling resolve is insufficient: traversal, sibling directories and symlinks can alter what is reached. The check must match the actual filesystem policy and opening strategy.

Common mistake

Normalization does not eliminate all symlink or race concerns.

Verify the behavior

Test another user’s ID, traversal, similar directory prefixes and symlink behavior.

Interview exercise

Handle user-selected downloads.

Answer and reasoning

Prefer validated opaque IDs mapped to authorized files, and enforce containment under the actual filesystem policy.

Continue learning

Compare the scenario with the Python interview questions and test your understanding with the Python MCQs. For terminology and implementation details, consult the reference material.

More in Python

read ✓Python · hard

Python asyncio.gather and Timeouts

Run coroutines concurrently with asyncio.gather, enforce timeouts, and handle partial failures and cancellation correctly.

~2 min readread →
read ✓Python · mid

Python Bounded Async Worker Queues

Use asyncio.Queue and a fixed worker pool to bound pending work. Trace backpressure, shutdown and failure ownership.

~3 min readread →
read ✓Python · mid

Python Asyncio and Blocking Functions

Python Asyncio and Blocking Functions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc