Is there an idiomatic way to add an extension using Python's Pathlib?

PythonPython 3.xPathlib

Python Problem Overview


I'm using Python's Pathlib and I want to take something like

p = Path('/path/to/foo')

And then try a couple of different extensions. I can do

for ext in ['.txt', '.md', '.note']
    filename = Path(str(p) + ext)

but that feels a little awkward. Is there a better way to do this?

Python Solutions


Solution 1 - Python

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).

Solution 2 - Python

You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like append_suffix

>>> python -m pip install pathlib3x

>>> import pathlib3x as pathlib

>>> pathlib.Path('some_path').append_suffix('.ext')
PosixPath('some_path.ext')

>>> pathlib.Path('some_path.ext.ext2').append_suffix('.ext3')
PosixPath('some_path.ext.ext2.ext3')

>>> pathlib.Path('some_path.ext').append_suffix('.tar.gz')
PosixPath('some_path.ext.tar.gz')


you can find it on github or PyPi


Disclaimer: I'm the author of the pathlib3x library.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWayne WernerView Question on Stackoverflow
Solution 1 - Pythonuser2357112View Answer on Stackoverflow
Solution 2 - PythonbitranoxView Answer on Stackoverflow