The with_suffix
method will return a new path with a different extension, either changing an existing extension or adding a new one. Examples from the docs:
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_suffix('.bz2')
PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
>>> p = PureWindowsPath('README')
>>> p.with_suffix('.txt')
PureWindowsPath('README.txt')
In your case, p.with_suffix(ext)
would do the job.
For cases where you need to add a suffix after any existing suffixes instead of removing existing suffixes, you can use p.with_suffix(p.suffix+ext)
. This is kind of clunky, though, and I don't know whether I would prefer it over Path(str(p)+ext)
.