I am moving some of my code from os.path
to pathlib.Path
and found that in general it is much better.
On a specific task I found that actually os.path
might be more comfortable to use. I want to create a new path from a given one, by adding a suffix to its name and keeping the same root and extension. For example, from:
/a/b/c/file.txt
I want to get:
/a/b/c/file_test.txt
Using os.path
, this can be done easily with splitext
:
>>> import os
>>> path = "/a/b/c/file.txt"
>>> base, ext = os.path.splitext(path)
>>> base + "_test" + ext
'/a/b/c/file_test.txt'
But, going over the pathlib
's docs, I found with_name
and with_suffix
and got something like:
>>> from pathlib import Path
>>> path = Path("/a/b/c/file.txt")
>>> path.with_suffix('').with_name(path.stem + "_test").with_suffix(path.suffix)
PosixPath('/a/b/c/file_test.txt')
Which I believe is far worse than the os.path
version.
Is there a better, cleaner way of achieving this with pathlib
?
Mixing some of your approaches, you can also do:
from pathlib import Path
path = Path("/a/b/c/file.txt")
path.with_name(path.stem + '_test' + path.suffix)
# PosixPath('/a/b/c/file_test.txt')