Sort temporary report paths by filename
Sort temporary report paths by filename
A program should not rely on an incidental directory enumeration order when it needs reports in a predictable sequence. This example creates three report files under one temporary directory, but deliberately puts their paths into an unsorted list. sorted(paths, key=lambda path: path.name) selects each final filename as the comparison key, yielding alpha.txt, summary.txt, and zeta.txt.
The first assertion compares the resulting filename list to the intended order. The second confirms that each result still has the same parent directory. Sorting creates a new list of the existing path objects; it does not rename, move, or rewrite the report files. Printing only the comma-joined names makes the output exact and hides the temporary directory location.
pathlib is available from Python 3.4, and TemporaryDirectory from Python 3.2. Path.name is the final component of a path; the pathlib documentation defines that property. This key produces ordinary string ordering, not natural numeric ordering: report-10.txt sorts before report-2.txt. Case behavior also follows normal Python string comparison rather than a locale-specific rule. The assertions demonstrate the stated filenames only; they do not show how to handle duplicate names from multiple directories. The TemporaryDirectory reference documents cleanup of this synthetic fixture.
AI-assistance disclosure: AI helped draft this educational article.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
reports = Path(directory) / "reports"
reports.mkdir()
paths = [
reports / "zeta.txt",
reports / "alpha.txt",
reports / "summary.txt",
]
for path in paths:
path.write_text("ready\n", encoding="utf-8")
ordered = sorted(paths, key=lambda path: path.name)
names = [path.name for path in ordered]
assert names == ["alpha.txt", "summary.txt", "zeta.txt"]
assert all(path.parent == reports for path in ordered)
print(",".join(names))
alpha.txt,summary.txt,zeta.txt
Comments
Post a Comment