10-16-2026, 02:41 PM
A filename containing several dots can make extension handling surprising. These single-line examples use PurePath, so they only manipulate path text and do not touch any files.
The three values are:
The final suffix is .gz; suffixes includes all the dot-separated suffix portions; stem removes only the last suffix. Notice that .2026 is included too: suffixes is not a detector of archive or compression formats.
Likewise, replacing the last suffix leaves the earlier portions intact:
This prints reports.2026.tar.zip. If the intention is to replace the known full ending .tar.gz, handle that exact ending explicitly:
This prints reports.2026.zip. The removesuffix example requires Python 3.9 or newer. Both operations return a new path value: they neither rename a file on disk nor convert its contents.
Reference: https://docs.python.org/3/library/pathlib.html
from pathlib import PurePath; p = PurePath("reports.2026.tar.gz"); print(p.suffix, p.suffixes, p.stem)The three values are:
.gz ['.2026', '.tar', '.gz'] reports.2026.tarThe final suffix is .gz; suffixes includes all the dot-separated suffix portions; stem removes only the last suffix. Notice that .2026 is included too: suffixes is not a detector of archive or compression formats.
Likewise, replacing the last suffix leaves the earlier portions intact:
print(p.with_suffix(".zip"))This prints reports.2026.tar.zip. If the intention is to replace the known full ending .tar.gz, handle that exact ending explicitly:
print(p.with_name(p.name.removesuffix(".tar.gz") + ".zip"))This prints reports.2026.zip. The removesuffix example requires Python 3.9 or newer. Both operations return a new path value: they neither rename a file on disk nor convert its contents.
Reference: https://docs.python.org/3/library/pathlib.html
