Remove a literal filename ending with removesuffix
Removing a known filename ending with rstrip(".txt") can erase part of the stem. It strips any trailing combination of those characters. Use removesuffix(".txt") when the entire suffix must match.
Set up
Tested on Linux with CPython 3.12.14. Use Bash, Python 3.12 or newer, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal open and stop if setup fails. Run without -O so the assertions remain enabled.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as literal_suffix.py:
names = ("report.txt", "text.txt", "text", "archive.txt.txt", "REPORT.TXT")
for name in names:
stripped = name.rstrip(".txt")
removed = name.removesuffix(".txt")
print(f"{name!r}: rstrip={stripped!r}, removesuffix={removed!r}")
assert "text.txt".removesuffix(".txt") == "text"
assert "text".removesuffix(".txt") == "text"
assert "archive.txt.txt".removesuffix(".txt") == "archive.txt"
assert "REPORT.TXT".removesuffix(".txt") == "REPORT.TXT"
assert "text".removesuffix("") == "text"
def required_stem(name):
if not name.endswith(".txt"):
raise ValueError("expected a .txt suffix")
return name.removesuffix(".txt")
try:
required_stem("text")
except ValueError as error:
print("Required suffix:", error)Run:
python3 -B literal_suffix.pyObserved output:
'report.txt': rstrip='repor', removesuffix='report'
'text.txt': rstrip='te', removesuffix='text'
'text': rstrip='te', removesuffix='text'
'archive.txt.txt': rstrip='archive', removesuffix='archive.txt'
'REPORT.TXT': rstrip='REPORT.TXT', removesuffix='REPORT.TXT'
Required suffix: expected a .txt suffixRemove one matching ending
The observed result for the report filename loses its final letter under character stripping. The shorter text filename loses two letters even when it has no extension. Literal suffix removal preserves both stems.
One call removes one occurrence. The repeated extension therefore leaves one extension behind. Matching is case-sensitive, and an absent suffix leaves the original text unchanged. The empty suffix also leaves the text unchanged; the assertion covers that boundary.
The string method reference describes literal suffix removal; rstrip() documents character-set stripping.
Validate a required suffix separately
If an import requires that extension, unchanged output is not enough to signal an error. The helper checks the ending before removing it and raises for the name without an extension. The caught exception is intentional.
These operations change strings only. They do not rename files, resolve paths, verify file formats, or make an untrusted path safe to open. An extension-only name would also produce an empty stem; reject that separately if your application requires a nonempty name.
Clean up
Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- literal_suffix.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.