Preserve a double suffix while naming an archive
A compound extension such as .tar.gz communicates more than one naming layer. If an archive copy of logs.tar.gz is named with only Path.stem and Path.suffix, it is easy to preserve .gz while accidentally relocating or losing .tar. This example instead joins source.suffixes to obtain .tar.gz, removes that exact ending from the filename, and inserts .archive before restoring both suffixes.
The resulting name is logs.archive.tar.gz. The assertions verify both that exact path name and that the synthetic payload was copied to the derived archive path. PurePath.suffixes returns all suffixes, whereas suffix returns only the last one. The str.removesuffix method removes its argument only when it is actually present, making the intended filename transformation clearer than a fixed slice.
Use Python 3.9+ here because str.removesuffix() was introduced in Python 3.9; pathlib itself is older. This convention treats every dot-separated suffix as meaningful, which may not match names like versioned files or hidden filenames. It also changes a name only; the explicit write_text copies sample text but is not a general archival process and preserves neither metadata nor binary data.
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:
source = Path(raw_directory) / "logs.tar.gz"
source.write_text("payload\n", encoding="utf-8")
suffixes = "".join(source.suffixes)
basename = source.name.removesuffix(suffixes)
archive = source.with_name(f"{basename}.archive{suffixes}")
archive.write_text(source.read_text(encoding="utf-8"), encoding="utf-8")
assert archive.name == "logs.archive.tar.gz"
assert archive.read_text(encoding="utf-8") == "payload\n"
print(archive.name)
logs.archive.tar.gz
Comments
Post a Comment