pythonpython-3.xpathlib

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


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?


Solution

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