Adding another suffix to a path that already has a suffix with pathlib Adding another suffix to a path that already has a suffix with pathlib python python

Adding another suffix to a path that already has a suffix with pathlib


I find the following slightly more satisfying than the answers that have already been given:

new_path = path.parent / (path.name + '.suffix')


You can just convert your Path to string then add new extension and convert back to Path:

from pathlib import Pathfirst = Path("D:/user/file.xy")print(first)second = Path(str(first)+".res")print(second)


It doesn't seem like Path's like being modified in-place (you can't change .parts[-1] directory or change .suffixes, etc.), but that doesn't mean you need to resort to anything too unsavory. The following works just fine, even if it's not quite as elegant as I'd like:

new_path = path.with_suffix(path.suffix + new_suffix)

where path is your original Path variable, and new_suffix is the string with your new suffix/extension (including the leading ".")