PurePath.with_suffix
The three with_* methods rewrite the final component: with_suffix swaps (or adds, or removes) the extension, with_stem keeps the extension, with_name replaces everything after the last slash. They are pure — nothing is renamed on disk.
Demo
from pathlib import PurePosixPath PurePosixPath('photos/cat.jpeg').with_suffix('.webp')
with_suffix works on the stem, so on site.tar.gz only .gz is replaced. A suffix without a leading dot is rejected, and so is any path with an empty name like '/'. with_stem('') on a file that has a suffix fails because the result would be just the extension. with_name refuses a name containing a slash — use / to add a sub-path instead.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| suffix | str | yes | with_suffix: '' removes the last suffix; otherwise it must start with '.' and be longer than one character. |
| stem | str | yes | with_stem: the new stem; the current suffix is appended. |
| name | str | yes | with_name: the complete new last component; must not be empty, '.', or contain a separator. |
Return value
PurePath — A new path of the same class; only the last component differs.
Common patterns
from pathlib import Path p = Path('draft.txt') p.rename(p.with_suffix('.md'))
from pathlib import Path for src in Path('images').glob('*.png'): convert(src, src.with_suffix('.webp'))
from pathlib import PurePosixPath p = PurePosixPath('backup.tar.gz') p.with_suffix('').with_suffix('.zip') # backup.zip
Examples
Pitfalls
from pathlib import PurePosixPath PurePosixPath('notes.txt').with_suffix('md')
from pathlib import PurePosixPath PurePosixPath('notes.txt').with_suffix('.md')
from pathlib import PurePosixPath PurePosixPath('.').with_name('out')
from pathlib import PurePosixPath PurePosixPath('.') / 'out'
from pathlib import Path p = Path('draft.txt') p.touch() p.with_suffix('.md') sorted(x.name for x in Path('.').iterdir())
from pathlib import Path p = Path('draft.txt') p.touch() p.rename(p.with_suffix('.md')) sorted(x.name for x in Path('.').iterdir())
When to use
- Deriving output file names from input names
- Changing, adding or removing an extension
- Renaming on disk → combine with rename() / replace()
- Adding a sub-path → the / operator
Notes
FAQ
p.with_suffix('.new') gives the new path; p.rename(p.with_suffix('.new')) renames the file. Include the dot.