You could just .split it:
>>> Path('logs/date.log.txt').stem.split('.')[0]
'date'
os.path works just as well:
>>> os.path.basename('logs/date.log.txt').split('.')[0]
'date'
It passes all of the tests:
In [11]: all(Path(k).stem.split('.')[0] == v for k, v in {
....: 'a': 'a',
....: 'a.txt': 'a',
....: 'archive.tar.gz': 'archive',
....: 'directory/file': 'file',
....: 'd.x.y.z/f.a.b.c': 'f',
....: 'logs/date.log.txt': 'date'
....: }.items())
Out[11]: True
Answer from Blender on Stack Overflowpython - Clean way to get the "true" stem of a Path object? - Stack Overflow
string - How do I get the filename without the extension from a path in Python? - Stack Overflow
python - Adding another suffix to a path that already has a suffix with pathlib - Stack Overflow
pathlib .suffix, .suffixes, .stem unexpected behavior for pathname with trailing dot
Videos
You could just .split it:
>>> Path('logs/date.log.txt').stem.split('.')[0]
'date'
os.path works just as well:
>>> os.path.basename('logs/date.log.txt').split('.')[0]
'date'
It passes all of the tests:
In [11]: all(Path(k).stem.split('.')[0] == v for k, v in {
....: 'a': 'a',
....: 'a.txt': 'a',
....: 'archive.tar.gz': 'archive',
....: 'directory/file': 'file',
....: 'd.x.y.z/f.a.b.c': 'f',
....: 'logs/date.log.txt': 'date'
....: }.items())
Out[11]: True
Why not go recursively?
from pathlib import Path
def true_stem(path):
stem = Path(path).stem
return stem if stem == path else true_stem(stem)
assert(true_stem('d.x.y.z/f.a.b.c') == 'f')
Python 3.4+
Use pathlib.Path.stem
>>> from pathlib import Path
>>> Path("/path/to/file.txt").stem
'file'
>>> Path("/path/to/file.tar.gz").stem
'file.tar'
Python < 3.4
Use os.path.splitext in combination with os.path.basename:
>>> os.path.splitext(os.path.basename("/path/to/file.txt"))[0]
'file'
>>> os.path.splitext(os.path.basename("/path/to/file.tar.gz"))[0]
'file.tar'
Use .stem from pathlib in Python 3.4+
from pathlib import Path
Path('/root/dir/sub/file.ext').stem
will return
'file'
Note that if your file has multiple extensions .stem will only remove the last extension. For example, Path('file.tar.gz').stem will return 'file.tar'.
I find the following slightly more satisfying than the answers that have already been given:
new_path = path.parent / (path.name + '.suffix')
EDIT: as @mitch-mcmabers pointed out, an even more satisfying answer would be
new_path = path.with_name(f"{path.name}.suffix")
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 ".")
» pip install extended-pathlib