Replace the final suffix of a generated report
Generated filenames often contain meaningful dots before their final extension. Given summary.final.txt, changing the output format to JSON should produce summary.final.json, not discard the final portion. Path.with_suffix(".json") performs exactly that final-suffix replacement and returns a new path object.
The fixture writes the original text report, derives the JSON destination, and writes a separate JSON placeholder. Its two assertions make the intended facts explicit: the derived name is summary.final.json, and the original text report remains unchanged. This follows the documented behavior of PurePath.with_suffix: it replaces the final suffix, appends one if absent, and removes the suffix when given an empty string. TemporaryDirectory supplies an isolated directory for the example.
This code works with Python 3.4+ because it uses pathlib APIs available from that release. A suffix is naming metadata, not proof of a file format. Renaming a path neither converts the original report’s content nor moves it; the sample explicitly writes a new file to make that distinction visible. Paths with no filename component can raise ValueError, and a compound name such as data.tar.gz has only .gz replaced by with_suffix.
AI-assistance disclosure: this article was drafted with AI assistance and should be reviewed in the context of its application.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as raw_directory:
report = Path(raw_directory) / "summary.final.txt"
report.write_text("ready\n", encoding="utf-8")
replacement = report.with_suffix(".json")
replacement.write_text("{}\n", encoding="utf-8")
assert replacement.name == "summary.final.json"
assert report.read_text(encoding="utf-8") == "ready\n"
print(replacement.name)
summary.final.json
Comments
Post a Comment