Return a readable CLI error when a report parent directory is missing

Quick answer

Opening a file does not create an absent parent directory; Path.open therefore raises FileNotFoundError for this requested path.

Example

The fixture targets missing/report.txt, catches that specific exception, and prints the stable parent-missing label. A CLI can put a readable version of that label on stderr and return its documented nonzero code.

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
    p = Path(d) / 'missing' / 'report.txt'
    try:
        p.open('x', encoding='utf-8')
    except FileNotFoundError:
        result = 'parent-missing'
    assert result == 'parent-missing'
    print(result)

Expected stdout:

parent-missing

Reading the result

Automatically creating parents is a different product decision. It may be convenient for a scratch directory but surprising when a typo would otherwise reveal a bad output path.

Distinguish a missing parent from a permission-denied parent in the CLI result. Both prevent output creation, but the corrective action is different and should not be guessed from one generic error label.

The example leaves the missing directory absent after the test. That proves the error handling did not quietly turn a path typo into a new filesystem location.

Sources

- Python pathlib documentation

Prepared with AI assistance. The example uses synthetic data; its stated limits apply.

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic